我一直在努力解决这个问题。我们通过Ajax调用我们的内部服务,Ajax会在请求完成后设置cookie。根据我目前所见,这可以通过withCredentials
参数完成。我还查看了Mozilla的例子
https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Requests_with_credentials
这指向了我。 http://arunranga.com/examples/access-control/credentialedRequest.html
看起来它正常工作我只需要正确设置CORS。但是,当我复制代码并尝试调用我的服务时,我没有看到任何cookie被设置。
这是代码。
var invocation = new XMLHttpRequest();
var url = 'MY SERVICE URL';
var invocationHistoryText;
function callOtherDomain(){
if(invocation)
{
invocation.open('GET', url, true);
invocation.withCredentials = "true";
invocation.onreadystatechange = handler;
invocation.send();
}
}
function handler(evtXHR)
{
if (invocation.readyState == 4)
{
if (invocation.status == 200)
{
var response = invocation.responseText;
console.log(response);
}
else
alert("Invocation Errors Occured" + invocation.readyState);
}
else
{
console.log("currently the application is at" + invocation.readyState);
}
}
这是我得到的回复
access-control-allow-credentials:true
access-control-allow-headers:Authorization, Content-Type, If-None-Match
access-control-allow-methods:GET, HEAD, POST, PUT, PATCH, DELETE, OPTIONS
access-control-allow-origin:http://localhost:8888
access-control-expose-headers:WWW-Authenticate, Server-Authorization
access-control-max-age:86400
cache-control:max-age=600
Connection:keep-alive
content-encoding:gzip
Content-Length:56
Content-Type:text/plain; charset=utf-8
Date:Thu, 07 Jul 2016 14:25:19 GMT
Expires:Thu, 07 Jul 2016 14:35:19 GMT
这是它制作的请求标题
请求标题
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:en-US,en;q=0.8,th;q=0.6,zh-CN;q=0.4,zh-TW;q=0.2
Cache-Control:no-cache
Connection:keep-alive
Cookie:name=Fe26.2**6cff63f4eb1d5d63c9ef3beb4618b19b4638f5a805030ac9e3e06f0f3561e6f1*gX0LowRnJ-Bc0YS5WAMFqQ*66rp6okC9kDZXmZ4rl8BVVlGOI_KcGlydCG-XnFmgUX4_e6CMeg6JCpjx12xEF5c**a454d2b7be5b7f32cc463aaf151f67fbeefedf4dbe0d389ba2fb19a1b6745ba3*XBh9bkxi6HLcB0zwm500nYjsiiUw7TRsCZB_p2xgln4
DNT:1
Host:MY INTERNAL SERVICE
Origin:http://localhost:8888
Pragma:no-cache
Referer:http://localhost:8888/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36
所以,我不确定这里有什么问题。