javascript Set-Cookie 标头未在 Chrome 中设置 cookie

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31058542/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 13:11:34  来源:igfitidea点击:

Set-Cookie header not setting cookie in Chrome

javascriptjqueryajaxgoogle-chromecookies

提问by MattA

I'm AJAXing a call to a another services API, which is then supposed to return a cookie that will be set in my browser to allow me to make the rest of my API calls.

我正在 AJAX 调用另一个服务 API,然后应该返回一个 cookie,该 cookie 将在我的浏览器中设置,以允许我进行其余的 API 调用。

However, while the response headers include a 'Set-Cookie' header, no cookie is ever actually set. I'm using Google Chrome.

然而,虽然响应标头包含一个“Set-Cookie”标头,但实际上没有设置任何 cookie。我正在使用谷歌浏览器。

Here is the Response Headers:

这是响应头:

Access-Control-Allow-Origin:*
Cache-Control:no-cache
Connection:keep-alive
Content-Encoding:gzip
Content-Length:37
Content-Type:application/json
Date:Thu, 25 Jun 2015 18:27:37 GMT
Expires:Thu, 25 Jun 2015 18:27:36 GMT
Server:nginx/1.4.6 (Ubuntu)
Set-Cookie:sessionid=67cb9796aa794a4975b28876ea6dd3d5; expires=Thu, 09-Jul-2015 18:27:37 GMT; httponly; Max-Age=1209600; Path=/
Vary:Cookie

And here is the AJAX call:

这是 AJAX 调用:

$.ajax({
            type: "POST",
            crossDomain: true,
            contentType: 'text/plain',
            data: data,
            url: urlhere 
            success: function(result, status, xhr){
                console.log('hi');
                console.log(xhr.getAllResponseHeaders());
            }, 
            error: function(xhr){
                console.log(xhr.status);
                console.log(xhr.statusText);
            }
});

The Chrome resources page also shows that no cookie is being set. Any and all help would be greatly appreciated!

Chrome 资源页面还显示未设置 cookie。任何和所有的帮助将不胜感激!

回答by SuperSaiyen

You need to append withCredentialsto your XHR call, this answer shows how to do that with jQuery. https://stackoverflow.com/a/7190487Without that additional flag, the browser will not accept a set-cookie header.

您需要附加withCredentials到您的 XHR 调用中,此答案显示了如何使用 jQuery 执行此操作。https://stackoverflow.com/a/7190487如果没有该附加标志,浏览器将不接受 set-cookie 标头。