我正在向API发出XMLHttpRequest,该API必须在参数验证后设置cookie。一切正常,返回Set-Cookie标头,但浏览器未设置cookie。在Firefox 62.0.3和Chrome 68.0.3440.84中进行了尝试。我的withCredentials标志为true。
我的XMLHttpRequest如下-
var invocation = new XMLHttpRequest();
var url = 'http://127.0.0.1/auth';
var invocationHistoryText;
var body = '{"email":"xxxx@gmail.com","password":"xxx@test"}';
function callOtherDomain(){
if(invocation)
{
invocation.open('POST', url, true);
invocation.withCredentials = "true";
invocation.setRequestHeader('Content-Type','application/json');
invocation.onreadystatechange = handler;
invocation.send(body);
}
else
{
invocationHistoryText = "No Invocation TookPlace At All";
var textNode = document.createTextNode(invocationHistoryText);
var textDiv = document.getElementById("textDiv");
textDiv.appendChild(textNode);
}
}
我的飞行前要求也很好。以下是其标题:
Preflight请求-
OPTIONS /auth HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type
Origin: http://xxx.000webhostapp.com
DNT: 1
Connection: close
前途反应-
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: http://xxx.000webhostapp.com
Vary: Origin
Access-Control-Allow-Credentials: true
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: Origin,X-Requested-With,Content-Type,Accept
Content-Length: 0
Date: Mon, 22 Oct 2018 01:10:21 GMT
Connection: close
发布请求-
POST /auth HTTP/1.1
Host: 127.0.0.1
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:62.0) Gecko/20100101 Firefox/62.0
Accept: */*
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Referer: http://xxx.000webhostapp.com/yyy.html
Content-Type: application/json
Content-Length: 57
Origin: http://xxx.000webhostapp.com
DNT: 1
Connection: close
{"email":"xxx@gmail.com","password":"xxx@test"}
帖子回复-
HTTP/1.1 200 OK
X-Powered-By: Express
Access-Control-Allow-Origin: http://xxx.000webhostapp.com
Vary: Origin
Access-Control-Allow-Credentials: true
Set-Cookie: coo=aa; Expires=Wed, 23 Oct 2018 07:28:00 GMT; HttpOnly
Content-Type: application/json; charset=utf-8
Content-Length: 368
ETag: W/"170-w78Ss5DUummozAsRbo5JsjFDoGI"
Date: Mon, 22 Oct 2018 01:10:22 GMT
Connection: close
{"data":{"firstName":"aaaa","lastName":"bbbb"},"Token":"ttt"}
但是浏览器未设置返回的cookie。
我接受了先前的建议-Cookies on localhost with explicit domain,How to correct set the cookies for a subdomain in JSP?和Set-Cookie header has no effect: about using cookies & CORS, including for localhost ("Access-Control-Allow-Headers")。基于这些,我从请求中删除了端口号(将服务器托管在80),并尝试将服务器移至在线HTTPS站点,但是没有任何效果。
任何帮助将不胜感激。