This issue is caused by CORS OPTIONS request in browser, which has nothing to do with axios. https://developer.nps.gov requires Authorization
header in all HTTP request, including OPTIONS. However, all custom HTTP headers will be excluded from OPTIONS, refer to https://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0
The National Park Service API should not require Authorization
header for OPTIONS request, but it does. Anyway, there is a workaround: make a forward-route in your own backend, accept the HTTP request from browser, retrieve data from https://developer.nps.gov in backend, and finally return it to browser.
Actually, send HTTP request with third party authorization key from browser is definitely not a good idea -- This design will expose your National Park Service API key to everyone who visit the page, which is certainly a dangerous thing.
Your first solution (config API key to axios default headers) is OK. I tried with my own API key and your URL, the response code is 200 OK.
For the second solution, the config
object should be used as headers
field in axios statement. The code would be:
axios.get('https://developer.nps.gov/api/v0/parks?parkCode=yell', {headers: config})
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…