Setting authorization header in axios

2020-02-14 04:00发布

问题:

I have been trying to make a GET request to the National Park Service API with axios and have tried several ways to set my API key in the request header to no avail. Any assistance will be greatly appreciated.

I have tried:

axios.defaults.headers.common['Authorization'] = "MY-API-KEY";
axios.get('https://developer.nps.gov/api/v0/parks?parkCode=yell')
.then((resp) => {
    console.dir(resp);
});

and

let config = {'Authorization': 'MY-API-KEY'};
axios.get('https://developer.nps.gov/api/v0/parks?parkCode=yell', config)
.then((resp) => {
    console.dir(resp);
});

and both return a 401. It works when I send the GET request in Postman, where I enter Authorization in the key field, and my API key in the value field.

Thank you.

回答1:

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})