記一次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配置:php

add_header Access-Control-Allow-Origin http://m.abc.com;

請求成功以後發現cookie沒法共享,在ajax裏帶上參數:nginx

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配置:ajax

add_header Access-Control-Allow-Credentials true;

至此正常訪問。json

 -------------------------2017.10.13 更新-----------------------------api

若是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.cookie

 -------------------------2017.05.23 更新-----------------------------post

爲了配合新增m的三級域名,調整api.abc.com的nginx配置:jsonp

 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/qbs.ssl.crt;
10     ssl_certificate_key  /etc/ssl/qbs.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 }
相關文章
相關標籤/搜索