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
// axios二次封装
import axios from "axios"; // 引入 axios
// import baseUrl from "./env"; // 基础url
import Vue from "vue";
import code from "./state_code"; // 状态码维护
import store from "@/store";
let that = new Vue();
const service = axios.create({
validateStatus(status) {
return status >= 200 && status <= 504; // 合法状态码
},
baseURL: process.env.VUE_APP_API, // 基础请求路径
timeout: 60000, // 请求超时
});
// 重复尝试此时
service.defaults.retry = 3;
// 重试延时
service.defaults.retryDelay = 15000;
// 开启重试
service.defaults.shouldRetry = true;
// 请求拦截
service.interceptors.request.use(
(config) => {
config.headers["Content-Type"] = "application/json;charset=UTF-8";
config.headers["Accept-Language"] = "zh-CN";
// token
config.headers["Authorization"] = store.state.common.token;
if (config.method === "post") {
if (!config.data) {
config.data = {};
}
}
store.commit("common/loadingShow", true);
return config;
},
(error) => {
const {
response: { status, statusText },
} = error;
that.$msg.error({
message: status,
description: statusText || "错误",
});
}
);
// response 拦截器
service.interceptors.response.use(
(response) => {
that.$msg.destroy(); //防止弹窗多次
store.commit("common/loadingShow", false);
return new Promise((resolve, reject) => {
if (response.status !== 200) {
// 请求失败
reject(response);
} else {
const { returnCode, returnMsg } = response.data || {};
// 判断token有效
const TOKENSTATE = code.TOKEN_INVLIDE_TO_LOGIN(returnCode);
// 全局错误拦截
const PUBSTATE = code.PUB_ERR(returnCode, returnMsg, response.config);
// 请求成功,但逻辑或者业务有错,返回具体数据,根据业务决定是否要提示 有token失效全局异常不返回
if (TOKENSTATE && PUBSTATE) {
const { config } = response
if (config && config.responseType === 'blob') {
resolve(response)
}else{
resolve(response.data);
}
}
}
}).catch(() => {
console.log("that?", response);
that.$msg.error({
message: response.config.url,
description: response.status + " : " + response.statusText,
});
});
},
(err) => {
store.commit("common/loadingShow", false);
// 失败
let message = "请求异常,请检测网络!";
if (err.response) {
message = err.response.data.message;
}
that.$msg.error({
message: message,
description: "错误",
});
}
);
export default service;