跨域请求默认是不会发送cookie的,要想获得cookie需要在前后端进行设置
- 前端:需要加上
withCredentials = true
var xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.xxx.com/api');
xhr.withCredentials = true;
xhr.onload = onLoadHandler;
xhr.send();
- 后端:需要设置
Access-Control-Allow-Credentials: true
注:Access-Control-Allow-Origin需要设置为白名单的形式,不能设置为Access-Control-Allow-Origin: *
注:Cookie依然遵循同源政策,只有用服务器域名设置的Cookie才会上传,其他域名的Cookie并不会上传,且(跨源)原网页代码中的document.cookie也无法读取服务器域名下的Cookie;