记一次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里带上参数:
1 crossDomain: true, 2 xhrFields:{ 3 withCredentials:true 4 },
出现错误:
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配置:
1 server { 2 listen 80; 3 listen 443; 4 server_name api.abc.com; 5 index index.php; 6 root /datas/htdocs/abc_api; 7 8 ssl on; 9 ssl_certificate /etc/ssl/ssl.crt; 10 ssl_certificate_key /etc/ssl/ssl.key; 11 12 location ~ .*\.php?$ { 13 set_by_lua $http_referer_test ' 14 if ngx.var.http_referer ~= nil then 15 tt = string.match(ngx.var.http_referer, "//%w+%.?m%.abc%.com"); 16 end 17 if tt == nil or tt == "" then 18 tt = "//m.abc.com"; 19 end 20 return tt; 21 '; 22 23 proxy_set_header X-Real-IP $remote_addr; 24 proxy_pass http://127.0.0.1:9504; 25 add_header Access-Control-Allow-Origin $scheme:$http_referer_test; 26 add_header Access-Control-Allow-Credentials true; 27 } 28 29 access_log /datas/log/www/access.abc_api.log main; 30 error_log /datas/log/www/error.abc_api.log; 31 }