我是靠谱客的博主 淡定仙人掌,这篇文章主要介绍解决跨域设置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无法生效。

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

最后

以上就是淡定仙人掌最近收集整理的关于解决跨域设置Cookie问题的全部内容,更多相关解决跨域设置Cookie问题内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(89)

评论列表共有 0 条评论

立即
投稿
返回
顶部