手撸一个简单版的axios
export default class Axios {
constructor(config) {
if (!Axios.instance) {
Axios.instance = this;
// 请求配置
this.config = {
baseUrl: "", // 基础路径
timeout: 30 * 1000, // 超时时间
...config,
};
// 响应会调方法
this.responseResovle = (data) => data;
// 请求执行回调
this.requestResovle = (data) => data;
// 响应错误回调
this.responseError = (data) => data;
// 拦截器
this.intercept = {
request: {
use: (resolve, error) => {
try {
if (
typeof resolve !== "function" ||
(error && typeof error !== "function")
) {
throw new Error("此方法应该接收两个函数");
}
this.requestResovle = resolve;
} catch (e) {
if (error) return error(e);
throw new Error(e || "参数错误");
}
},
},
response: {
use: (resolve, error) => {
if (
typeof resolve !== "function" ||
(error && typeof error !== "function")
) {
throw new Error("此方法应该接收两个函数");
}
resolve && (this.responseResovle = resolve);
error && (this.responseError = error);
},
},
};
}
return Axios.instance;
}
// 静态-获取实例方法
static getInstance(config) {
if (!this.instance) {
return (this.instance = new Axios(config));
}
return this.instance;
}
// 重新发送方法
reSend = (options, resolve, reject) => {
console.log("reSend", options);
return uni.request({
...options,
success: (res) => {
resolve(this.responseResovle(res));
},
fail: (e) => {
reject(this.responseError(e));
},
});
};
// 发送
send = (args) => {
let config = {};
if (typeof args === "object") {
config = {
...JSON.parse(JSON.stringify(this.config)),
...args,
};
}
config = this.requestResovle(config); // 将config交给拦截器回调函数
return new Promise((resolve, reject) => {
config = {
...config,
url: config.baseUrl + (config.url || ""),
method: config.method.toUpperCase(), // 配置method方法
};
uni.request({
...config,
success: (res) => {
resolve(
this.responseResovle({
...res,
config: config,
})
);
},
fail: (e) => {
reject(
this.responseError({
...res,
config: config,
})
);
},
});
}).catch((e) => {
return e;
});
};
}
使用方法
// 单例模式-创建Axios实例
let axios = new Axios.getInstance({
timeout: 30 * 1000,
baseUrl: BASE_URL + apiUrl,
});
/**
* @param {*} options,
* @returns Promise
*/
axios.post = (options) => {
return axios.send({
...options,
method: "post",
});
};
/**
* @param {*} options,
* @returns Promise
*/
axios.get = (options) => {
return axios.send({
...options,
method: "get",
});
};
// 请求拦截
axios.intercept.request.use((config) => {
// to do something
return config;
});
// 响应拦截
axios.intercept.response.use(
(res) => {
// to do something
return res
},
(res) => {
return {
meta: {
code: 400,
msg: res?.meta?.msg
},
};
}
);
版权声明:本文为weixin_41217541原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。