谷歌浏览器不传递cookie(登录验证码总是失效)
1. 在谷歌浏览器中搜索chrome://flags/
2. 在出现的页面搜索框中搜索SameSite
3. 把第一个改为disabled
4. 然后重启浏览器
vue项目中完美封装fetch
env.js文件,如下:
/**
* 配置编译环境和线上环境之间的切换
*
* baseUrl: 域名地址
* routerMode: 路由模式
* imgBaseUrl: 图片所在域名地址
*
*/
let baseUrl = '';
let routerMode = 'hash';
let imgBaseUrl = '';
if (process.env.NODE_ENV == 'development') {
imgBaseUrl = '/img/';
}else if(process.env.NODE_ENV == 'production'){
baseUrl = '//elm.cangdu.org';
imgBaseUrl = '//elm.cangdu.org/img/';
}
export {
baseUrl,
routerMode,
imgBaseUrl,
}
fetch.js文件,如下:
import { baseUrl } from './env'
export default async(url = '', data = {}, type = 'GET', method = 'fetch') => {
type = type.toUpperCase();
url = baseUrl + url;
// 此处规定get请求的参数使用时放在data中,如同post请求
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;
}
}
// 对于支持fetch方法的浏览器,处理如下:
if (window.fetch && method == 'fetch') {
let requestConfig = {
// fetch默认不会带cookie,需要添加配置项credentials允许携带cookie
credentials: 'include',
method: type,
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
mode: "cors", // 以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 { // 对于不支持fetch的浏览器,便自动使用 ajax + promise
return new Promise((resolve, reject) => {
let requestObj;
if (window.XMLHttpRequest) {
requestObj = new XMLHttpRequest();
} else {
requestObj = new ActiveXObject; // 兼容IE
}
let sendData = '';
if (type == 'POST') {
sendData = JSON.stringify(data);
}
requestObj.open(type, url, true);
requestObj.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
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)
}
}
}
})
}
}