Javascript 如何使用 axios 发送授权标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44245588/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send authorization header with axios
提问by foobar
How can I send an authentication header with a token via axios.js? I have tried a few things without success, for example:
如何通过 axios.js 发送带有令牌的身份验证标头?我尝试了一些没有成功的事情,例如:
const header = `Authorization: Bearer ${token}`;
return axios.get(URLConstants.USER_URL, { headers: { header } });
Gives me this error:
给我这个错误:
XMLHttpRequest cannot load http://localhost:8000/accounts/user/. Request header field header is not allowed by Access-Control-Allow-Headers in preflight response.
I have managed to get it work by setting global default, but I'm guessing this is not the best idea for a single request:
我已经通过设置全局默认值设法让它工作,但我猜这不是单个请求的最佳主意:
axios.defaults.headers.common['Authorization'] = `Bearer ${token}`;
Update :
更新 :
Cole's answer helped me find the problem. I am using django-cors-headers middlewarewhich already handles authorization header by default.
科尔的回答帮助我找到了问题所在。我正在使用django-cors-headers 中间件,默认情况下它已经处理了授权标头。
But I was able to understand the error message and fixed an error in my axios request code, which should look like this
但是我能够理解错误消息并修复了我的 axios 请求代码中的错误,它应该如下所示
return axios.get(URLConstants.USER_URL, { headers: { Authorization: `Bearer ${data.token}` } });
采纳答案by Cole Erickson
On non-simple http requests your browser will send a "preflight" request (an OPTIONS method request) first in order to determine what the site in question considers safe information to send (see herefor the cross-origin policy spec about this). One of the relevant headers that the host can set in a preflight response is Access-Control-Allow-Headers. If any of the headers you want to send were not listed in either the spec's list of whitelisted headers or the server's preflight response, then the browser will refuse to send your request.
对于非简单的 http 请求,您的浏览器将首先发送“预检”请求(OPTIONS 方法请求),以确定相关站点认为要发送的安全信息(有关此的跨域策略规范,请参见此处)。主机可以在预检响应中设置的相关标头之一是Access-Control-Allow-Headers. 如果您要发送的任何标头未在规范的白名单标头列表或服务器的预检响应中列出,则浏览器将拒绝发送您的请求。
In your case, you're trying to send an Authorizationheader, which is not considered one of the universally safe to send headers. The browser then sends a preflight request to ask the server whether it should send that header. The server is either sending an empty Access-Control-Allow-Headersheader (which is considered to mean "don't allow any extra headers") or it's sending a header which doesn't include Authorizationin its list of allowed headers. Because of this, the browser is not going to send your request and instead chooses to notify you by throwing an error.
在您的情况下,您正在尝试发送一个Authorization标头,这不被认为是普遍安全的发送标头之一。然后浏览器发送一个预检请求,询问服务器是否应该发送该标头。服务器要么发送一个空Access-Control-Allow-Headers标头(这被认为意味着“不允许任何额外的标头”),要么它正在发送一个不包含Authorization在其允许标头列表中的标头。因此,浏览器不会发送您的请求,而是选择通过抛出错误来通知您。
Any Javascript workaround you find that lets you send this request anyways should be considered a bug as it is against the cross origin request policy your browser is trying to enforce for your own safety.
您发现任何允许您发送此请求的 Javascript 解决方法都应被视为错误,因为它违反了您的浏览器为了您自己的安全而试图强制执行的跨源请求策略。
tl;dr- If you'd like to send Authorizationheaders, your server had better be configured to allow it. Set your server up so it responds to an OPTIONSrequest at that url with an Access-Control-Allow-Headers: Authorizationheader.
tl;dr- 如果您想发送Authorization标头,您的服务器最好配置为允许它。设置您的服务器,以便它OPTIONS使用Access-Control-Allow-Headers: Authorization标头响应该 url 上的请求。
回答by Matija ?upan?i?
Try this :
尝试这个 :
axios.get(
url,
{headers: {
"name" : "value"
}
}
)
.then((response) => {
var response = response.data;
},
(error) => {
var status = error.response.status
}
);
回答by sean717
This has worked for me:
这对我有用:
let webApiUrl = 'example.com/getStuff';
let tokenStr = 'xxyyzz';
axios.get(webApiUrl, { headers: {"Authorization" : `Bearer ${tokenStr}`} });
回答by Canaan Etai
Rather than adding it to every request, you can just add it as a default config like so.
您可以像这样将其添加为默认配置,而不是将其添加到每个请求中。
axios.defaults.headers.common['Authorization'] = `Bearer ${access_token}`
回答by Jalasem
You are nearly correct, just adjust your code this way
您几乎是正确的,只需以这种方式调整您的代码
const headers = { Authorization: `Bearer ${token}` };
return axios.get(URLConstants.USER_URL, { headers });
notice where I place the backticks, I added ' ' after Bearer, you can omit if you'll be sure to handle at the server-side
注意我放置反引号的位置,我在 Bearer 之后添加了 ' ',如果您确定在服务器端处理,则可以省略
回答by Deepak
Instead of calling axios.get function Use:
而不是调用 axios.get 函数使用:
axios({ method: 'get', url: 'your URL', headers: { Authorization: `Bearer ${token}` } })
回答by MESDOUR
res.setHeader('Access-Control-Allow-Headers',
'Access-Control-Allow-Headers, Origin,OPTIONS,Accept,Authorization, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers');
Blockquote : you have to add OPTIONS & Authorization to the setHeader()
Blockquote :您必须将 OPTIONS & Authorization 添加到 setHeader()
this change has fixed my problem, just give a try!
这个改变解决了我的问题,试试吧!
回答by ringing-bell
Install the corsmiddleware. We were trying to solve it with our own code, but all attempts failed miserably.
安装cors中间件。我们试图用我们自己的代码来解决它,但所有的尝试都以惨败告终。
This made it work:
这使它起作用:
cors = require('cors')
app.use(cors());
回答by Ashish
You can try this.
你可以试试这个。
axios.get(
url,
{headers: {
"Access-Control-Allow-Origin" : "*",
"Content-type": "Application/json",
"Authorization": `Bearer ${your-token}`
}
}
)
.then((response) => {
var response = response.data;
},
(error) => {
var status = error.response.status
}
);
回答by edthebedhead
Derric's page is very helpful to describe how CORS and preflight and GET requests work, especially in the circumstances where you are try to use a GET with an authorization header. https://www.moesif.com/blog/technical/cors/Authoritative-Guide-to-CORS-Cross-Origin-Resource-Sharing-for-REST-APIs/#
Derric 的页面非常有助于描述 CORS 以及预检和 GET 请求的工作方式,尤其是在您尝试使用带有授权标头的 GET 的情况下。 https://www.moesif.com/blog/technical/cors/Authoritative-Guide-to-CORS-Cross-Origin-Resource-Sharing-for-REST-APIs/#
I wasn't able to get any of the chrome brower plugins to work, however I was able to start Chrome without security and with out CORS, so the preflight request is NOT sent with the GET+Authorization header.
我无法让任何 chrome 浏览器插件工作,但是我能够在没有安全性和没有 CORS 的情况下启动 Chrome,因此预检请求不会与 GET+Authorization 标头一起发送。
On Windows 10 command will be:
在 Windows 10 上命令将是:
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp
"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe" --disable-web-security --disable-gpu --user-data-dir=~/chromeTemp
Thanks to: https://alfilatov.com/posts/run-chrome-without-cors/

