cookie通常不能跨域,但是有時(shí)候我們不得不使用,因此通過查資料發(fā)現(xiàn)cookie經(jīng)過特殊處理也是可以跨域的。
首先服務(wù)端需要支持跨域,通常已經(jīng)處理過了,否則請求都無法進(jìn)行。
在客戶端設(shè)置分為兩種,原生的XMLHttpRequest請求方法如下:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://localhost:8888/interface/test", true);
xhr.withCredentials = true; //這一句是關(guān)鍵
xhr.send();
使用ajax請求方法如下:
$.ajax({
type: "GET",
url: "http://localhost:8888/interface/test",
xhrFields: {
withCredentials: true //這一句是關(guān)鍵
},
crossDomain: true,
})
通過特殊處理后,cookie也可以跨域使用了。