解决跨域设置Cookie问题

如a.123.com跨域访问b.123.com、

b.123.com服务器使用nginx允许跨域,Access-Control-Allow-Origin:*

如果a、b服务不在同一个服务器

前台页面请求报错信息为: 

Access to XMLHttpRequest at 'http://b.123.com' 
from origin 'http://a.123.com' has been blocked by CORS policy: 
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'. 
The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

对应ajax请求为: 


$.ajax({
        url : 'http://b.123.com/request',
        data : data,
        dataType: 'json',
        type : 'POST',
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        ...

此时,应取消nginx设置的跨域*,改成代码端设置。且代码服务器端通过在响应 header 中设置 

response.setHeader("Access-Control-Allow-Credentials", "true");

来运行客户端携带证书式访问。通过对 Credentials 参数的设置,就可以保持跨域 Ajax 时的 Cookie。

服务器端 Access-Control-Allow-Credentials = true时,Access-Control-Allow-Origin 的值不能为 '*' ,应设置为发起请求的地址。

如a.com发来的请求:

response.setHeader("Access-Control-Allow-Origin", a.123.com);

如c.123.com发来的请求:

response.setHeader("Access-Control-Allow-Origin", c.123.com);

b服务器在设置cookie时,需设置

cookie.setPath("/");

cookie.setDomain("123.com");

否则设置的cookie无法生效。

欢迎访问个人主页:唐悦玮的博客

  • 5
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Tangyuewei

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值