request.js
3.65 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
import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import Cookies from 'js-cookie';
const CONTENT_TYPE = "application/json";
// create an axios instance
const service = axios.create({
baseURL: process.env.VUE_APP_BASE_API, // url = base url + request url
// withCredentials: true, // send cookies when cross-domain requests
headers: {
"content-type": CONTENT_TYPE,
},
timeout: 50000 // request timeout
})
// request interceptor
service.interceptors.request.use(
config => {
config.headers['token'] = Cookies.get('token')
return config
},
error => {
console.log(error) // for debug
return Promise.reject(error)
}
)
// response interceptor
service.interceptors.response.use(
response => {
const res = response.data
const { code } = res
if (code === undefined) {
return res
}
// if the custom code is not 20000, it is judged as an error.
if (code !== 200) {
if (code === 600) {
Message({
message: res.message || 'Error',
type: 'error',
duration: 5 * 1000
})
} else if (code === 402) {
MessageBox.confirm('登录已失效,可以取消继续留在该页面,或者重新登录', '确定登出', {
confirmButtonText: '重新登录',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
store.dispatch('user/resetToken').then(() => {
location.reload()// 为了重新实例化vue-router对象 避免bug
})
})
} else if (code === 401) {
store.dispatch('user/resetToken').then(() => {
location.reload()// 为了重新实例化vue-router对象 避免bug
})
} else if (code === 403) {
if (res.message == 'Bad credentials') {
Message({
message: '账号、密码输入有误',
type: 'error',
duration: 5 * 1000
})
} else {
Message({
message: res.message,
type: 'error',
duration: 5 * 1000
})
}
}
else {
Message({
message: '服务器异常,请联系管理员',
type: 'error',
duration: 5 * 1000
})
}
// 401:未登录;
return Promise.reject('error')
} else {
return res
}
},
error => {
let str = '600'; //新增了token 返回状态码为600
if (error.toString().indexOf(str) !== -1) {
MessageBox.confirm('登录已失效,可以取消继续留在该页面,或者重新登录', '确定登出', {
confirmButtonText: '重新登录',
cancelButtonText: '取消',
type: 'warning'
}).then(() => {
store.dispatch('user/resetToken').then(() => {
location.reload()// 为了重新实例化vue-router对象 避免bug
})
})
} else {
Message({
message: '服务器异常,请联系管理员',
type: 'error',
duration: 5 * 1000
})
}
return Promise.reject(error)
}
)
export default service