如何在 JavaScript 中使用 XMLHttpRequest 设置 Cookie(标头)?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2320110/
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 do I SET a Cookie (header) with XMLHttpRequest in JavaScript?
提问by barryred
I'm trying to set a Cookie in a XSS request using XMLHttpRequest.
我正在尝试使用 XMLHttpRequest 在 XSS 请求中设置 Cookie。
I found the XMLHttpRequest Specification, and section 4.6.2-5 does seem to suggest that setting Cookie, Cookie2, and some other headers are not allowed, but I was hoping there was a work around.
我找到了XMLHttpRequest Specification,第 4.6.2-5 节似乎确实建议设置 Cookie、Cookie2 和其他一些标头是不允许的,但我希望有解决方法。
My (jQuery) code is below, but the resulting query fails as the cookie is NOT set.
我的 (jQuery) 代码如下,但由于未设置 cookie,结果查询失败。
$.ajax( {
type : "POST",
url : URL,
data: SOAP_INBOX_MAIL_QUERY,
dataType : "xml",
async: false,
beforeSend : function(xhr) {
var cookie = credentials["COOKIE"];
console.info( "adding cookie: "+ cookie );
xhr.setRequestHeader('Cookie', cookie);
},
success : function(data, textStatus, xmLHttpRequest){
},
error : function(xhr, ajaxOptions, thrownError) {
credentials = null;
}
});
回答by terrycojones
This can be done. You need the following in the $.ajax call:
这是可以做到的。在 $.ajax 调用中需要以下内容:
xhrFields: {
withCredentials: true
}
(See the jQuery docs), and you'll also need the site you're making the request to to support CORS (they will at least need to allow you origin and also to set the Access-Control-Allow-CredentialsHTTP header to true).
(请参阅 jQuery 文档),并且您还需要您请求支持 CORS 的站点(他们至少需要允许您使用 origin 并将Access-Control-Allow-CredentialsHTTP 标头设置为true)。
There's no question it works. You can do it over HTTPS, with Basic Auth, etc. jQuery will send everything (the auth header, cookies) if you tell it to (xhrFields) and the site provides the right CORS headers. Don't give up!
毫无疑问它有效。您可以通过 HTTPS、Basic Auth 等来完成。如果您告诉它 (xhrFields) 并且站点提供正确的 CORS 标头,jQuery 将发送所有内容(身份验证标头、cookie)。不要放弃!
回答by Gabriel McAdams
For security reasons, you will be unable to modify the header during an XMLHTTPRequest.
出于安全原因,您将无法在 XMLHTTPRequest 期间修改标头。
回答by phorgan1
If you set the cookie using document.cookie then when you send the request the cookie header will include it.
如果您使用 document.cookie 设置 cookie,那么当您发送请求时,cookie 标头将包含它。
回答by loocao
https://developer.mozilla.org/En/Server-Side_Access_Control
https://developer.mozilla.org/En/Server-Side_Access_Control
allow you origin and also to set the Access-Control-Allow-Credentials HTTP header to true
允许您来源并将 Access-Control-Allow-Credentials HTTP 标头设置为 true
回答by antyrat
If your request at the same domain as jquery code, you can use jquery cookies plugin
如果您的请求与 jquery 代码在同一域,则可以使用 jquery cookie 插件

