跨域请求携带cookie

之前写过一个第三方登录的方案,就是利用tomcat session和cookie配合的方式来完成第三方跨域登录。在时间做的过程中碰到了一个问题,就是在回写浏览器的cookie时发现一直写不进去,针对这个问题做了仔细的检查,原来的采用ajax发送跨域请求的时候默认是不会携带cookie的,如果需要允许服务端写入cookie,需要对请求做设置,允许请求携带cookie。

xhrFields: { withCredentials: true }

例子如下:

$(document).ready(function() {
$.ajax({
 type: "post",
 url: 'http://xxx.com?sessionId=e34842383',
 async: false, // 使用同步方式
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 xhrFields: { withCredentials: true },
 success: function (data) {
if (200 === data.code) {
 alert(data.result);
 location.href = data.result;
} else {
 location.href = "xxx";
}
 } // 注意不要在此行增加逗号
});


    });

当发送跨域的ajax请求中有 withCredentials: true这个属性设置时,如果服务端有回写cookie,则在浏览器的cookie中可以看到该cookie,记录一下。

参考:

https://blog.csdn.net/vincent_ling/article/details/51714691

https://www.cnblogs.com/zhuotiabo/p/6230521.html


猜你喜欢

转载自blog.csdn.net/w450093854/article/details/80548989