
正文
记一次header跨域与cookie共享
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
最近把左边的传统模式,换成了右边通过js直接调api拿数据并渲染,于是变出现了ajax的跨域问题:
XMLHttpRequest cannot load http://api.abc.com/?s=user/account_log&v=1.0. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://m.abc.com' is therefore not allowed access.
api项目都为post请求且返回结果为json,为了不改动api,于是没用jsonp,而是采用header,修改api.abc.com的nginx配置:
add_header Access-Control-Allow-Origin http://m.abc.com;
请求成功之后发现cookie无法共享,在ajax里带上参数:
crossDomain: true,
xhrFields:{
withCredentials:true
},
出现错误:
XMLHttpRequest cannot load http://api.abc.com/?s=user/account_log&v=1.0. The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'. Origin 'http://m.abc.com' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
再次修改api.abc.com的nginx配置:
add_header Access-Control-Allow-Credentials true;
至此正常访问。
-------------------------2017.10.13 更新-----------------------------
如果Access-Control-Allow-Origin配置的是通配的 * ,这里还会报另一个错误
Failed to load http://api.abc.com/?s=user/account_log&v=1.0: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. Origin 'http://m.abc.com' is therefore not allowed access. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.
-------------------------2017.05.23 更新-----------------------------
为了配合新增m的三级域名,调整api.abc.com的nginx配置:
server {
listen ;
listen ;
server_name api.abc.com;
index index.php;
root /datas/htdocs/abc_api;
ssl on;
ssl_certificate /etc/ssl/ssl.crt;
ssl_certificate_key /etc/ssl/ssl.key;
location ~ .*\.php?$ {
set_by_lua $http_referer_test '
if ngx.var.http_referer ~= nil then
tt = string.match(ngx.var.http_referer, "//%w+%.?m%.abc%.com");
end
if tt == nil or tt == "" then
tt = "//m.abc.com";
end
return tt;
';
proxy_set_header X-Real-IP $remote_addr;
proxy_pass http://127.0.0.1:9504;
add_header Access-Control-Allow-Origin $scheme:$http_referer_test;
add_header Access-Control-Allow-Credentials true;
}
access_log /datas/log/www/access.abc_api.log main;
error_log /datas/log/www/error.abc_api.log;
}






