axios.js
2.67 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
import axios from "axios"
import Cookies from "js-cookie"
import NProgress from "nprogress"
import { Message } from "element-ui"
import router from "@/router/index"
import store from "@/store"
import conf from "../config/index"; // 路径配置
// 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;
// if (Cookies.get("access_token")) {
// config.headers.Authorization = "Bearer" + Cookies.get("access_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) {
// Cookies.set("access_token", response.data.message, { expires: 1 / 12 })
// console.log(response.status)
if (res.code == 999) {
if (!location.href.includes('localhost')) {
if (res.data) {
window.location.href = res.data
} else {
router.push({ path: '/login' })
if (res.message.includes('不存在')) {
Message({
message: res.message,
type: 'error',
duration: 3 * 1000
})
}
}
}
return
} else {
// Cookies.set("access_token", response.data.message, { expires: 1 / 12 })
}
}
return Promise.resolve(response)
},
error => {
Message({
message: error.message,
type: 'error',
duration: 3 * 1000
})
if (error.response == undefined) {
return Promise.reject(error);
}
Message.closeAll()
const {
data,
status
} = error.response
if (status === 403 || status === 401) {
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
}
return Promise.reject(error.response) // 返回接口返回的错误信息
})
export default service