Setting up the authorization header in axios

I'm trying to make a National Park API GET request using axioms and have tried multiple ways to set the API key in the request header to no avail. Any help would be much appreciated.

I 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 401. It works when I send a GET request to Postman where I enter authorization in the key field and the API key in the values โ€‹โ€‹field.

Thank.

+3


source to share


1 answer


This issue is caused by a CORS OPTIONS request in the browser which has nothing to do with axioms. https://developer.nps.gov requires a header Authorization

in the entire HTTP request, including OPTIONS. However, all custom HTTP headers will be excluded from OPTIONS, see https://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0

The National Parks API shouldn't require a header Authorization

for the OPTIONS request, but it does. Anyway, there is a workaround: do the redirect in your own backend, accept the HTTP request from the browser, fetch the data from https://developer.nps.gov in the backend, and finally return it to the browser.

In fact, it is definitely not a good idea to send an HTTP request using a third party authorization key from the browser. This project will expose your Service Pack API to everyone who visits the page, which is definitely dangerous.




Your first solution (config API key for axios headers) is fine. I tried using my own API key and your url, response code 200 OK.

For the second solution, the object config

should be used as a field headers

in the axios statement. The code will look like this:

axios.get('https://developer.nps.gov/api/v0/parks?parkCode=yell', {headers: config})

      

+4


source







All Articles