我爱编程

跨域请求时携带cookie信息

2018-07-10  本文已影响0人  氕氘氚0921

cookie通常不能跨域,但是有时候我们不得不使用,因此通过查资料发现cookie经过特殊处理也是可以跨域的。
首先服务端需要支持跨域,通常已经处理过了,否则请求都无法进行。
在客户端设置分为两种,原生的XMLHttpRequest请求方法如下:

var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:8888/interface/test", true);
xhr.withCredentials = true;  //这一句是关键
xhr.send();

使用ajax请求方法如下:

$.ajax({
    type: "GET",
    url: "http://localhost:8888/interface/test",
    xhrFields: {
        withCredentials: true //这一句是关键
    },
    crossDomain: true,
})

通过特殊处理后,cookie也可以跨域使用了。

上一篇 下一篇

猜你喜欢

热点阅读