我有两个子词"api.domain.com"和"web.domain.com"。现在"web.domain.com"是用html/javascript编写的网页,"api.domain.com"是用php编写的简单restful API服务器。
"api.domain.com"在标头中设置某些 cookie,如下所示
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Credentials: true");
setcookie("TestCookie", "Some Value", time()+3600, "/", ".domain.com", 0);
现在,当我从"web.domain.com"到"api.domain.com"进行ajax调用(使用jQuery.ajax(((时,响应标头包含
Set-Cookie:abc=802691344656c1d0899c4a74.87956617; expires=Mon, 16-May-2016 21:00:09 GMT; path=/; domain=domain.com,
所以我想应该在客户端浏览器中的"web.domain.com"处设置一个cookie。
下次我从"web.domain.com"再次向"api.domain.com"发出请求时,这个cookie不应该作为请求标头的一部分吗?
但是,当我在"api.domain.com"处检查 $_COOKIE 数组时,我没有看到这个 cookie!这是否意味着 cookie 从未首先在客户端("web.domain.com"(中设置?我做错了什么?
使用 withCredentials 标头(如 @charlietfl 建议的那样(对我有用。我也不得不在服务器中进行另一项修改。这就是我所做的。在 web.domain.com 中,在对 Ajax 请求进行修改时,我添加了 withCredentials:true ,像这样
$.ajax({
// The Url for the request
url : ajaxUrl,
// The data to send (will be converted to a query string)
data : ajaxData,
xhrFields: {
// To allow cross domain cookies
withCredentials: true
},
...
});
在 api.domain.com 中,我设置了一些这样的标题:
header("Access-Control-Allow-Origin: *");
但是,我仍然无法得到任何回应。我反而收到了此错误
Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true.
所以我只是将标头设置为源域,如下所示:
$http_origin = $_SERVER['HTTP_ORIGIN'];
if (substr($input, -10) == 'domain.com') { // To check if request is always from a subdomain of 'domain.com'
header("Access-Control-Allow-Origin: $http_origin");
}
这解决了问题。