// 通用请求拦截器
import axios from "axios";
import Qs from "qs";
import store from "@/store";
import router from "@/router";
import { Loading, Message } from "element-ui"; // 引用element-ui的加载和消息提示组件
let loading = null;
// 添加公共请求拦截
const interceptorsReq = (config) => {
loading = Loading.service({ text: "拼命加载中" });
const token = store.getters.token;
if (token) {
config.headers.Authorization = "Bearer " + token; // 请求头部添加token
}
};
// 添加公共响应拦截
const interceptorsRes = (response) => {
if (loading) {
loading.close();
}
if (response.data.code && response.data.code === 50000) {
alert("您的账户已在其他设备登录,如不是本人操作,请及时更改密码");
//router.push('/login')
store.commit("DEL_TOKEN");
router.replace({
path: "/login",
query: {
redirect: router.currentRoute.fullPath,
},
});
sessionStorage.clear();
location.reload();
return false;
}
if (response.data.code === 500001) {
Message.error("请求接口过于频繁,请三秒后再试");
return false;
}
const code = response.status;
if ((code >= 200 && code < 300) || code === 304) {
return Promise.resolve(response.data);
} else {
return Promise.reject(response);
}
};
const createInstance = (baseURL, interceptorsFn) => {
const instance = axios.create({
baseURL,
timeout: 30000,
});
instance.interceptors.request.use(
(config) => {
// 添加公共处理函数
interceptorsReq(config);
// interceptorsFn.interceptorsReq(config);
return config;
},
(error) => {
return Promise.reject(error);
}
);
instance.interceptors.response.use(
(response) => {
// 添加公共处理函数
interceptorsRes(response);
// interceptorsFn.interceptorsRes(response);
return response.data;
},
(error) => {
if (loading) {
loading.close();
}
console.log(error);
return Promise.reject(error);
}
);
return instance;
};
// 对不同环境的VUE_APP环境进行动态创建不同的axios实例导出
// 对于复杂的实例可以使用interceptorsFn参数进行扩展
let apiMap = {};
let instanceMap = {};
for (const apiKey in process.env) {
const url = process.env[apiKey];
const instanceName = apiKey.replace("VUE_APP_", "").toLocaleLowerCase();
// 子元素为http链接
if (url.startsWith("http")) {
// 动态设置aixos实例
apiMap[instanceName] = url;
instanceMap[instanceName] = createInstance(url);
createInstance(url).post = (url, data)=>{
post(url, data)
};
createInstance(url).get = (url, params)=>{
get(url, params)
};
}
}
console.log(apiMap);
console.log(instanceMap);
function post(url, data) {
return $axios({
method: "post",
url,
data: Qs.stringify(data),
headers: {
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
},
});
}
function get(url, params) {
return $axios({
method: "get",
url,
params,
});
}
// createInstance
// // get,post请求方法
export default {
...instanceMap
};
标签:axios,return,url,动态创建,vue,const,data,response
From: https://www.cnblogs.com/brujie/p/17916426.html