ajax 跨域请求session丢失

251 阅读1分钟

为什么跨域请求的时候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,
})

 示例:

 $.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: http://www.xxx.com");  // 允许该域跨域访问