Javascript 如何将基本身份验证标头分配给 XMLHTTPREQUEST?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33505130/
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 assign basic authentication header to XMLHTTPREQUEST?
提问by carrots
I've read many answers of preflight and CORS so please do not post links referencing what I should read. Many of the answers are from a server-perspective, but I am the client in this case. Do I set the origin header? My assumption is that this is a simple request, am I right?
我已经阅读了许多预检和 CORS 的答案,所以请不要发布引用我应该阅读的内容的链接。许多答案都是从服务器的角度来看的,但在这种情况下,我是客户。我是否设置了原始标题?我的假设是这是一个简单的请求,对吗?
req.open("POST", url, true);
req.setRequestHeader( 'Content-Type', 'application/blahblah' );
req.setRequestHeader( 'Accept', 'application/blahblah' );
req.setRequestHeader("Authorization", "Basic " + btoa(user + ":" + pass));
req.send();
Yet its still not working, my error:
然而它仍然无法正常工作,我的错误:
Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 500.
对预检请求的响应未通过访问控制检查:请求的资源上不存在“Access-Control-Allow-Origin”标头。因此,不允许访问 Origin 'null'。响应的 HTTP 状态代码为 500。
采纳答案by carrots
Solution:
解决方案:
req.setRequestHeader('Authorization', 'Basic [base64 encoded password here]' );
回答by epascarello
If you want to set the authorization header
如果要设置授权头
req.setRequestHeader('Authorization','Basic ' + Base64StringOfUserColonPassword);
回答by skinnysoftware
This post is old, but answering for anybody else who comes across it.
这篇文章很旧,但为其他遇到它的人回答。
There is nothing wrong with your authorization header. The problem you are facing is CORS related.
您的授权标头没有任何问题。您面临的问题与 CORS 相关。
You don't set the Origin header yourself. The browser does that for you. If your origin is null then I suspect this is because you are running your code from file:///
instead of http://
.
您不会自己设置 Origin 标头。浏览器会为你做这件事。如果您的原点为空,那么我怀疑这是因为您正在运行您的代码file:///
而不是http://
.
回答by Nick Spicer
If using this for an API request, adding the Authorization header will first make XMLHttpRequest send an OPTIONS request, which may be denied by some APIs.
如果将其用于 API 请求,则添加 Authorization 标头将首先使 XMLHttpRequest 发送一个 OPTIONS 请求,该请求可能会被某些 API 拒绝。
To get around this you can also do:
要解决此问题,您还可以执行以下操作:
var invocation = new XMLHttpRequest();
invocation.open("GET", url, true, username, password);
invocation.withCredentials = true;
Which will add the Authorization header and also avoid the preflight request.
这将添加 Authorization 标头并避免预检请求。