手撸一个简单版的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);
return new Promise((resolve, reject) => {
config = {
...config,
url: config.baseUrl + (config.url || ""),
method: config.method.toUpperCase(),
};
uni.request({
...config,
success: (res) => {
resolve(
this.responseResovle({
...res,
config: config,
})
);
},
fail: (e) => {
reject(
this.responseError({
...res,
config: config,
})
);
},
});
}).catch((e) => {
return e;
});
};
}
使用方法
let axios = new Axios.getInstance({
timeout: 30 * 1000,
baseUrl: BASE_URL + apiUrl,
});
axios.post = (options) => {
return axios.send({
...options,
method: "post",
});
};
axios.get = (options) => {
return axios.send({
...options,
method: "get",
});
};
axios.intercept.request.use((config) => {
return config;
});
axios.intercept.response.use(
(res) => {
return res
},
(res) => {
return {
meta: {
code: 400,
msg: res?.meta?.msg
},
};
}
);
|