ajax 跨域请求session丢失

网友投稿 1065 2022-10-10

ajax 跨域请求session丢失

ajax 跨域请求session丢失

为什么跨域请求的时候session会丢失?

关键先认识一下XMLHttpRequest.withCredentials属性。  引用MDN:

XMLHttpRequest.withCredentials 属性是一个Boolean类型,它指示了是否该使用类似cookies,authorization headers(头部授权)或者TLS客户端证书这一类资格证书来创建一个跨站点访问控制(cross-site Access-Control)请求。默认值是false

如果在发送来自其他域的XMLHttpRequest请求之前,  未设置withCredentials为true,那么就不能为它自己的域设置cookie值。  而通过设置withCredentials为true获得的第三方cookies,将会依旧享受同源策略,因此不能被通过document.cookie或则头部相应请求的脚本等访问。

注:永远不会影响到同源请求

Note: 不同域下的XMLHttpRequest相应,不论其Access-Control-header设置什么值, 都无法为它自身站点设置cookie值,除非在它请求之前将withCredentials设为true。

MDN案例(原生js):

var xhr = new XMLHttpRequest();xhr.open('GET', 'true);xhr.withCredentials = true;xhr.send(null);

Jquery:

$.ajax({ type: "POST", url: " dataType: 'jsonp', xhrFields: {withCredentials: true}, crossDomain: true,})

示例:

$.ajax({ type:"get", url:porject.host+data.url, data:data.parm, //dataType: 'jsonp', xhrFields: {withCredentials: true}, crossDomain: true, success:function(dat){ $(".n132").empty().append(JSON.stringify(dat)); }, error:function(XMLHttpRequest, textStatus, errorThrown){ $(".n132").empty().append("error"+XMLHttpRequest+textStatus+errorThrown); return; } });

服务端设置:header("Access-Control-Allow-Credentials: true"); // 是否支持cookie跨域header("Access-Control-Allow-Origin: // 允许该域跨域访问

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:开发小程序投诉「微信小程序投诉举报」
下一篇:wechat-lifecat:lifecat图像系统的WeChat端小程序
相关文章

 发表评论

暂时没有评论,来抢沙发吧~