在 axios 中设置授权头 [英] Setting authorization header in axios

查看:49
本文介绍了在 axios 中设置授权头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用 axios 向 National Park Service API 发出 GET 请求,并尝试了多种方法来在请求标头中设置我的 API 密钥,但均无济于事.任何帮助将不胜感激.

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.

我试过了:

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

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

并且都返回 401.当我在 Postman 中发送 GET 请求时,它会起作用,我在密钥字段中输入授权,在值字段中输入我的 API 密钥.

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.

谢谢.

推荐答案

此问题是浏览器中的 CORS OPTIONS 请求引起的,与 axios 无关.https://developer.nps.gov 在所有 HTTP 请求中都需要 Authorization 标头,包括选项.但是,所有自定义 HTTP 标头都将从 OPTIONS 中排除,请参阅 https://www.w3.org/TR/cors/#cross-origin-request-with-preflight-0

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

国家公园服务 API 不应该要求 OPTIONS 请求的 Authorization 标头,但它确实需要.无论如何,有一个解决方法:在您自己的后端创建一个转发路由,接受来自浏览器的 HTTP 请求,从 https 检索数据://developer.nps.gov 在后端,最后返回给浏览器.

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.

实际上,从浏览器发送带有第三方授权密钥的 HTTP 请求绝对不是一个好主意——这种设计会将您的 National Park Service API 密钥暴露给访问该页面的每个人,这当然是一件危险的事情.

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.

您的第一个解决方案(配置 axios 默认标头的 API 密钥)没问题.我尝试使用我自己的 API 密钥和您的 URL,响应代码是 200 OK.

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.

对于第二种解决方案,config 对象应该用作 axios 语句中的 headers 字段.代码将是:

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

这篇关于在 axios 中设置授权头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆