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', 'http://example.com/', true);
xhr.withCredentials = true;
xhr.send(null);

Jquery:

 $.ajax({
    type: "POST",
    url: "http://xxx.com/api/test",
    dataType: 'jsonp',
    xhrFields: {withCredentials: true},
    crossDomain: true,
})

服务端设置:

header("Access-Control-Allow-Credentials: true");       // 是否支持cookie跨域

header("Access-Control-Allow-Origin: http://www.xxx.com");  // 允许该域跨域访问

猜你喜欢

转载自blog.csdn.net/mangoyiy/article/details/79799539