场景: 使用 XMLHttpRequest 请求登录
Bug: 浏览器无法自动添加 cookie, 同事手动设置进入之后,其他请求之后浏览器无法自动携带信息,导致接口出错
解决: 帮忙查看之后,找了蛮久才在MDN发现原因:
不同域下的XmlHttpRequest 响应,不论其Access-Control- header 设置什么值,都无法为它自身站点设置cookie值,除非它在请求之前将withCredentials 设为true。
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open('POST', '接口', true);
xmlhttp.setRequestHeader('Content-type', 'application/json');
// 原因
xmlhttp.withCredentials = true;
xmlhttp.send(JSON.stringify(params));
xmlhttp.onreadystatechange = function () {
if (xmlhttp.status === 200 && xmlhttp.readyState == 4) {
const status = JSON.parse(xmlhttp.responseText);
if (+status.code === 0) {
}
}
};
教训: 花了长时间,基础还是不够牢固.有时间需要巩固下基础