vue request拦截处理
程序员文章站
2022-09-14 16:14:03
记录下import Vue from "vue";import axios from "axios";import { MessageBox, Message } from "element-ui";import store from "@/store";import qs from "qs";// create an axios instanceconst service = axios.create({ baseURL: process.env.VUE_APP_BASE_API, /...
记录下
import Vue from "vue";
import axios from "axios";
import { MessageBox, Message } from "element-ui";
import store from "@/store";
import qs from "qs";
// create an axios instance
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API,
timeout: 5000,
header: {
"Content-Type": "application/json; charset=utf-8"
}
});
// request interceptor
service.interceptors.request.use(
config => {
let href = window.location.href;
let index = href.lastIndexOf("/");
let path = href.substring(index);
if (config.method === "post") {
if (config.headers["Content-Type"] === "multipart/form-data") {
let formData = new FormData();
for (let key in config.data) {
formData.append(key, config.data[key]);
}
config.data = formData;
} else {
if (config.data) {
config.data = qs.stringify(config.data);
}
}
}
if (store.getters.token) {
config.headers['X-Token'] = "";
config.headers['X-Path'] = path;
}
return config;
},
error => {
console.log(error);
return Promise.reject(error);
}
);
service.interceptors.response.use(
response => {
let res = response.data;
if (typeof res == "string") {
res = res.substring(0, res.indexOf("}")) + "}";
res = JSON.parse(res);
}
if (res.code !== 0) {
Message({
message: res.message || "Error",
type: "error",
duration: 5 * 1000
});
if (res.code === 1000) {
// to re-login
MessageBox.alert("你已经退出了,请重新登录", "确定退出", {
confirmButtonText: "重新登录",
type: "warning"
}).then(() => {
});
}
return Promise.reject(new Error(res.message || "Error"));
} else {
return res;
}
},
error => {
console.log("err" + error);
message: error.message,
type: "error",
duration: 5 * 1000
});
return Promise.reject(error);
}
);
export default service;
本文地址:https://blog.csdn.net/xnlzg/article/details/107160241
上一篇: SQL语句入门必学
下一篇: 脾胃不好吃什么 调理脾胃的6款食疗方