在实际工作中我们一般会根据项目的需求对axios做二次封装,下面讲一讲我在工作中怎么封装axios的,这次加入了axios的取消请求功能
1、新建axios文件夹,内含http.js、index.js、config.js、apis文件夹:http.js用于封装axios,apis文件夹里是每个模块需要的请求接口,我们把所有的接口都写在这里,这样以后在需要修改的时候就不用每个文件里去找了,index.js是这个模块的导出文件,config.js是一些配置常量
2、http.js
import axios from "axios";
import { toast } from "@/com_js/utils";
const CancelToken = axios.CancelToken;
var pendingAxios = [];
let getAxiosKey = config => {
let param,
url = config.url,
method = config.method.toLocaleLowerCase();
if (
config.data &&
(method === "put" || method === "post" || method === "patch")
) {
param = JSON.stringify(config.data);
} else if (config.params) {
param = JSON.stringify(config.params);
}
return `${url}${method}${param}`;
};
let removePending = config => {
let s = pendingAxios.find(v => v.key === getAxiosKey(config));
if (s) {
s.f();
pendingAxios.splice(s, 1);
}
};
const instance = axios.create({
timeout: 10000,
withCredentials: true
});
instance.interceptors.request.use(
req => {
removePending(req);
req.cancelToken = new CancelToken(c => {
pendingAxios.push({ key: getAxiosKey(req), f: c });
});
return req;
},
error => Promise.reject(error)
);
instance.interceptors.response.use(
res => {
if (res.status === 200 && res.statusText === "OK") {
const data = res.data;
if (data.code == 0) {
return data;
} else {
toast(data.msg, "error");
return Promise.reject(res.data);
}
}
return Promise.reject(res);
},
error => {
if (error.response) {
toast("网络开小差,请稍后再试!", "error");
}
return Promise.reject(error);
}
);
const pandaAxios = param => {
return instance(param).then(
res => res,
error => {
console.error(param.url, param.method, ":::", error);
}
);
};
export default pandaAxios;
3、config.js:很多时候不同模块的请求地址是不一样的,所以没有在axios里配置basicUrl,而是config里配置,有时候整个项目会有自己的config.js文件,可以根据自己的需要决定把常量放在哪个文件里
const config = {
loginUrl:'',
defaultUrl:''
};
export default config;
4、index.js:导入其他模块的请求
import indexApi from "./apis/index";
import mainApi from "./apis/main";
export { indexApi, mainApi };
5、apis文件下的index.js
import axios from "@/axios/http";
import config from "@/axios/config";
const index = {
login() {
return axios({
url: "${config.loginUrl}/todo"
});
}
};
export default index;
6、在需要的.vue文件里调用login登录
import { indexApi } from '@/axios/index';
export default {
data() {
return {};
},
methods: {
async login() {
let res = await indexApi({...});
}
}
};