axios.js
2.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
import axios from "axios";
import NProgress from "nprogress";
import { Message } from "element-ui";
import router from "@/router/index";
import store from "@/store";
import conf from "../config/index"; // 路径配置
import { getURLParams } from "@/utils";
let code = getURLParams("code") || getURLParams("dockkey") || localStorage.getItem("csCode") || "";
// axios默认配置
const service = axios.create({
baseURL: conf.baseURL, // api的base_url
timeout: 600000000000000, // 请求超时时间
withCredentials: true,
});
// http request 拦截器
service.interceptors.request.use(
(config) => {
NProgress.start();
// config.headers["Content-Type"] = "application/json;charset=UTF-8";
const source = axios.CancelToken.source();
store.commit("setTokenSources", [source.token, source.cancel]);
config.cancelToken = source.token;
return config;
},
(error) => {
return Promise.reject(error.response);
}
);
// http response 拦截器
service.interceptors.response.use(
(response) => {
const res = response.data;
NProgress.done();
if (response.config.cancelToken) {
store.commit("delTokenSources", response.config.cancelToken);
}
if (response.status == 200) {
if (res.status == 999) {
// if (!location.href.includes("localhost")) {
if (res.data) {
window.location.href = res.data;
} else {
router.push({ path: "/login" });
if (res.info.includes("不存在")) {
Message({
info: res.info,
type: "error",
duration: 3 * 1000,
});
}
}
// }
}
}
return Promise.resolve(res);
},
(error) => {
const { data, status } = error.response;
if (error.response == undefined) {
return Promise.reject(error);
}
if (status === 403 || status === 401) {
if (data.status === 999) {
if (data.data) {
window.location.href = data.data;
} else {
Message({
message: data.info,
type: "error",
duration: 3 * 1000,
});
router.push({ path: "/login" });
}
if (code) {
return
} else {
return Promise.resolve(data);
}
}
Message.closeAll();
Message({
message: data.info || "未登录或登录超时,即将跳转到登录页面",
type: "error",
duration: 3 * 1000,
});
if (!window.location.href.includes("login")) {
router.push({
path: "/login",
query: {
url: window.location.href,
},
});
}
return;
}
Message({
message: data.info || error,
type: "error",
duration: 3 * 1000,
});
return Promise.reject(error.response); // 返回接口返回的错误信息
}
);
export default service;