为了应对活动的巨大流量,最近我们把活动相关的代码切到了一个新站点(act.xiaoying.com),和主站(www.xiaoying.com)相同父域。
下面的代码示例都是在测试环境写的调试代码 :)
Ajax 请求相同父域无法带上cookie
对 Ajax 的用法了解不够全面,一直只用jQuery 里面常用的几个属性。act.xiaoying.com下面有一个 domain=.xiaoying.com
的 cookie,请求www.xiaoying.com 不属于跨域,在我以前的想法里在发起请求的时候这个 cookie 是会被带上的,然而实测并没有。
1 | //ajax 请求代码 |
查看请求:
很显然cookie里面的 a 没有被带上。到StackOverflow上面找了一下,最后在 MDN 上面找到了withCrentials属性。
里面提到 ajax 的这个参数会影响 cookie 的传输,无论CORS 配的是什么。
在options 配置里面将这个参数加上:
1 | options.xhrFields = { |
再请求的时候查看请求cookie 是带上了,却报错(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'
)
万能的*
居然不行(笑容逐渐消失)。。。见招拆招,修改 nginx 配置:
1 | # 生产环境的 CORS 配置会复杂很多,测试环境简单设置成$http_origin |
再请求,继续报错 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'
:
心累,在cgi加上 Access-Control-Allow-Credentials
:
1 | header("Access-Control-Allow-Credentials:true"); |
再次请求,done。
太长不看
nginx
1 | add_header Access-Control-Allow-Origin $http_origin; #生产环境请自行添加 CORS策略 |
javascript
1 | options.xhrFields = { |
上面两段可以解决相同父域 cookie携带和写入的问题。不同父域的试了是不行的,还是另寻他法吧~