目录
一、特点
- 可以类似axios一样对网络请求的统一拦截
- 统一使用Promise方式返回
- 文件上传和网络请求使用统一拦截器处理
- 支持请求的取消
二、使用教程
1.新建HttpUtil.js文件
代码如下所示:
//构建短的uuid
function generateShortUUID() {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let shortUUID = '';
for (let i = 0; i < 8; i++) {
const randomIndex = Math.floor(Math.random() * chars.length);
shortUUID += chars.charAt(randomIndex);
}
return shortUUID;
}
//二次封装网络请求
export default class HttpUtil {
//请求的默认配置
#config = {
baseUrl: "",
timeout: 60000
};
//请求任务队列,结构如下:{type:{uuid:task}}
#requestTask = {};
//拦截器
#interceptors = {
preRequest: undefined,
preReponse: undefined,
errorReponse: undefined
}; //拦截器,支持单个拦截够用了
constructor(config) {
if (config) {
this.#config = config;
}
this.#requestTask = {};
}
get(url, data) {
return this.request({
url,
data,
method: "GET",
});
}
post(url, data) {
return this.request({
url,
data,
method: "POST",
});
}
put(url, data) {
return this.request({
url,
data,
method: "PUT",
});
}
delete(url, data) {
return this.request({
url,
data,
method: "DELETE",
});
}
/**
* 拦截器-发送请求前
* @param {*} preRequest 返回修改后的config
*/
useRequestInterceptor(preRequest) {
this