在用户提出了CORS请求而没有正确设置Cookie的StackOverflow上存在很多问题。我遇到了同样的问题,但是我想知道Chrome或其他浏览器是否提供了一种诊断和了解为什么未设置Cookie的方法。
我发现各种可能导致这种情况的原因:缺少CORS标头,缺少withCredentails=true
,跨越https安全边界的情况,Cookie上的某些标志...我想了解Chrome在做什么只是猜测为什么它不起作用。
这是我的特定问题,但实际上我正在寻找一个不仅要解决问题的方法。
注意withCredentails = true。
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState === XMLHttpRequest.DONE) {
callback(xmlhttp);
}
};
xmlhttp.open('POST', url, true);
xmlhttp.withCredentials = true;
xmlhttp.setRequestHeader('Content-Type', 'application/json');
xmlhttp.send(payload);
请注意,Chrome浏览器不会显示该请求的任何Set-Cookie标头。
但是如果我右键单击>复制> cUrl并在此处执行,则原始标头包括Set-Cookie:
curl 'http://satellite:6988/medic/login' -H 'Referer: http://upstream:5988/medic/login?redirect=http%3A%2F%2Fupstream%3A5988%2Fmedic%2F_design%2Fmedic%2F_rewrite%2F%23%2Fmessages%2Fcontact%3A13863168-be61-418a-aea1-1b19b9a5af39' -H 'Origin: http://upstream:5988' -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36' -H 'Content-Type: text/plain;charset=UTF-8' --data-binary '{"user":"worker","password":"dSNH1sv2jzdB"}' --compressed -v
* Trying 127.0.0.1...
* TCP_NODELAY set
* Connected to satellite (127.0.0.1) port 6988 (#0)
> POST /medic/login HTTP/1.1
> Host: satellite:6988
> Accept: */*
> Accept-Encoding: deflate, gzip
> Referer: http://upstream:5988/medic/login?redirect=http%3A%2F%2Fupstream%3A5988%2Fmedic%2F_design%2Fmedic%2F_rewrite%2F%23%2Fmessages%2Fcontact%3A13863168-be61-418a-aea1-1b19b9a5af39
> Origin: http://upstream:5988
> User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36
> Content-Type: text/plain;charset=UTF-8
> Content-Length: 43
>
* upload completely sent off: 43 out of 43 bytes
< HTTP/1.1 200 OK
< X-Powered-By: Express
< Access-Control-Allow-Origin: http://upstream:5988
< Vary: Origin, Accept-Encoding
< Access-Control-Allow-Methods: GET, POST, PUT, OPTIONS, HEAD, DELETE
< Access-Control-Allow-Headers: accept, authorization, content-type, origin, referer, x-csrf-token
< Access-Control-Allow-Credentials: true
< Set-Cookie: AuthSession=d29ya2VyOjVDMDdEMjgwOj06hJxoYrYGtUxNa3ImYd1AZ7Vw; Path=/
< Set-Cookie: userCtx=%7B%22name%22%3A%22worker%22%2C%22roles%22%3A%5B%22chv%22%5D%7D; Max-Age=31536000; Path=/; Expires=Thu, 05 Dec 2019 13:28:32 GMT
< Set-Cookie: satelliteServer=; Path=/; Expires=Thu, 01 Jan 1970 00:00:00 GMT
< Content-Type: application/json; charset=utf-8
< Content-Length: 16
< ETag: W/"10-oV4hJxRVSENxc/wX8+mA4/Pe4tA"
< Date: Wed, 05 Dec 2018 13:28:32 GMT
< Connection: keep-alive
<
* Connection #0 to host satellite left intact
{"success":true}
答案 0 :(得分:1)
Chrome控制台有助于理解CORS标头的问题。因为当请求被完全阻止时,它会写入清晰的描述性标头。
对于我的特定情况,我使用chrome:// net-internals /#events包含与cookie相关的事件,以了解Set-Cookie标头已从开发人员工具中省略,但已被提供,接收和正确设置。 / p>
我的问题是,设置Cookie后,我在请求上使用options.credentials=true
时设置了fetch
,而不是必需的options.credentials='include'
。