即使ajax请求的响应包含“Set-Cookie”头,cookie也不会存储在浏览器中。
请求代码:
function hitLogin(){
var loginUrl = "http://myapp:8080/login";
var geturl;
$.ajax({
type: "GET",
url : loginUrl,
data: {
user : "user1",
password : "encryptedPassword"
},
headers: {
"credentials": 'include',
"withCredentials" : true,
"crossDomain": true,
"X-Requested-With" : "XMLHttpRequest",
"Content-type" : "application/x-www-form-urlencoded",
"Accept":"text/plain",
},
success : function(data)
{
alert("Ajax request data: "+data);
},
error: function( xhr, status, error )
{
alert("Ajax request error: "+status );
}
});
}
收到的响应头:
Access-Control-Allow-Credentials:true
Access-Control-Allow-Headers:X-Requested-With,accept,content-type,Cookie
Access-Control-Allow-Methods:POST,GET,PUT,OPTIONS,DELETE
Access-Control-Allow-Origin:http://myapp2.com:7011
Access-Control-Max-Age:3600
Content-Encoding:gzip
Content-Type:text/plain;charset=ISO-8859-1
Date:Wed, 06 Jun 2018 15:10:09 GMT
Server:Apache-Coyote/1.1
Set-Cookie:MYCOOKIE=62lml5_S7qS31KaFDg-SH-e8Ds5FPjljCIHzfmhxMAr8Fdrqr6fHLjI7s2XPAO2P3tNFLNLS1_fgvDXF4pLmfg#1s1S1#normal-false; Path=/; HttpOnly
Transfer-Encoding:chunked
Vary:Accept-Encoding
withCredentials:true
我可以在浏览器中访问相同的URL时看到存储的cookie,但是在ajax请求的情况下,它没有被存储。因此无法发送需要该cookie的后续请求。
withCredentials: true
XHR字段就可以了。它只需要放在正确的位置,即xhrFields
中,而不是headers
中。 - Ilmari Karonen