Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

http - Setting authorization header in axios

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...