fetch请求对IE不友好,而Vue3也IE不友好,那么之后在创建Vue3项目的时候是不是可以尝试用Vue3 + fetch去代替axios呢?
当然也不知道行不行,所以先记录下我对fetch的封装。
首先引入封装请求的常用模块 - qs
npm install qs
简单封装下fetch请求 - 没什么好说的直接上代码
/**
* 配置请求
*/
// 导入模块
import qs from 'qs';
// URL地址 - 这边是接口的前缀 - 根据实际情况自行引入
import { BASE_URL } from './config.js';
/** 封装fetch请求 */
function sendFetch(url, params = null, method = 'GET') {
return new Promise(async (resolve, reject) => {
// 配置的参数
let config = {
headers: {
'token': localStorage.getItem('token') || "",
},
};
// 判断请求类型
if(method.toUpperCase() === 'GET' || method.toUpperCase() === 'DELETE') {
if(params) {
url += "?" + qs.stringify(params);
}
}
else if(method.toUpperCase() === 'POST' || method.toUpperCase() === 'PUT') {
config = {
method,
headers: {
'Content-Type': 'application/json',
...config.headers,
},
};
if(params) {
config = {
...config,
body: JSON.stringify(params),
};
}
}
try {
const response = await fetch(BASE_URL + url, {
mode: 'cors',
...config,
});
response.json().then(res => {
resolve(res);
}).catch(error => {
reject(error);
});
} catch(error) {
reject(error);
}
});
}
// 导出配置好的对象
export default sendFetch;