AJAX/Fetch 在跨域情况下发送cookie并保持 sessionid一致

Ajax

ajax在跨域发送请求的时候需要添加 xhrFields

1
2
3
4
5
6
7
8
9
10
11
12
13
$.ajax({
url:'example.com',
method:'post',
datatype:'json',
xhrFields: {
withCredentials: true
},
crossDomain: true,
data:param,
success:function(data){
console.log(data);
}
})

Fetch

fetch在跨域发送请求的时候需要添加 credentials: “include”

1
2
3
4
5
6
7
8
9
10
fetch('http://example.com',{
method:'post',
mode:'cors',
credentials: "include",
body: param
}).then((response)=>{
return response.json();
}).then((responseData)=>{
console.log(responseData);
});

参考:
Ajax跨域请求,同时保证session一致
Fetch API with Cookie