我尝试在登录时验证权限。服务器使用set-cookie进行响应,但浏览器没有保存cookie,尽管我设置了标题'凭据'与'包括'。
这是我的代码。
const baseUrl = '';
export default async(url = '', data = {}, type = 'GET', method = 'fetch') => {
type = type.toUpperCase();
url = baseUrl + url;
if (type === 'GET') {
let dataStr = '';
Object.keys(data).forEach(key => {
dataStr += `${key}=${data[key]}&`;
});
if (dataStr !== '') {
dataStr = dataStr.substr(0, dataStr.lastIndexOf('&'));
url = `${url}?${dataStr}`;
}
}
if (window.fetch && method === 'fetch') {
const requestConfig = {
credentials: 'include',
method: type,
headers: {
Accept: 'application/json',
'Content-Type': '*/*'
},
mode: 'cors',
cache: 'force-cache'
};
if (type === 'POST') {
Object.defineProperty(requestConfig, 'body', {
value: JSON.stringify(data)
});
}
try {
const response = await fetch(url, requestConfig);
const responseJson = await response.json();
return responseJson;
} catch (error) {
throw new Error(error);
}
} else {
return new Promise((resolve, reject) => {
let requestObj;
if (window.XMLHttpRequest) {
requestObj = new XMLHttpRequest();
} else {
requestObj = new ActiveXObject();
}
let sendData = '';
if (type === 'POST') {
sendData = JSON.stringify(data);
}
requestObj.open(type, url, true);
requestObj.setRequestHeader();
requestObj.send(sendData);
requestObj.onreadystatechange = () => {
if (requestObj.readyState === 4) {
if (requestObj.status === 200) {
let obj = requestObj.response;
if (typeof obj !== 'object') {
obj = JSON.parse(obj);
}
resolve(obj);
} else {
reject(requestObj);
}
}
};
});
}
};
然后我获取网址和服务器响应确定并设置cookie。当我在浏览器中检查cookie时,它不存在。这确实让我很困惑。那么我该如何解决这个问题呢。