commit | author | age
|
9bcb19
|
1 |
import Vue from 'vue' |
I |
2 |
import axios from 'axios' |
|
3 |
import store from '@/store' |
|
4 |
// import router from './router' |
|
5 |
import { message, Modal, notification } from 'ant-design-vue' /// es/notification |
|
6 |
import { VueAxios } from './axios' |
|
7 |
import { ACCESS_TOKEN } from '@/store/mutation-types' |
|
8 |
|
|
9 |
// 创建 axios 实例 |
|
10 |
const service = axios.create({ |
|
11 |
baseURL: '/api', // api base_url |
|
12 |
timeout: 6000 // 请求超时时间 |
|
13 |
}) |
|
14 |
|
|
15 |
const err = (error) => { |
|
16 |
if (error.response) { |
|
17 |
const data = error.response.data |
|
18 |
const token = Vue.ls.get(ACCESS_TOKEN) |
|
19 |
|
|
20 |
if (error.response.status === 403) { |
|
21 |
console.log('服务器403啦,要重新登录!') |
|
22 |
notification.error({ |
|
23 |
message: 'Forbidden', |
|
24 |
description: data.message |
|
25 |
}) |
|
26 |
} |
|
27 |
if (error.response.status === 500) { |
|
28 |
if (data.message.length > 0) { |
|
29 |
message.error(data.message) |
|
30 |
} |
|
31 |
} |
|
32 |
if (error.response.status === 401 && !(data.result && data.result.isLogin)) { |
|
33 |
if (token) { |
|
34 |
store.dispatch('Logout').then(() => { |
|
35 |
setTimeout(() => { |
|
36 |
window.location.reload() |
|
37 |
}, 1500) |
|
38 |
}) |
|
39 |
} |
|
40 |
} |
|
41 |
} |
|
42 |
return Promise.reject(error) |
|
43 |
} |
|
44 |
|
|
45 |
// request interceptor |
|
46 |
service.interceptors.request.use(config => { |
|
47 |
const token = Vue.ls.get(ACCESS_TOKEN) |
|
48 |
if (token) { |
|
49 |
config.headers['Authorization'] = 'Bearer ' + token |
|
50 |
} |
|
51 |
return config |
|
52 |
}, err) |
|
53 |
|
|
54 |
/** |
|
55 |
* response interceptor |
|
56 |
* 所有请求统一返回 |
|
57 |
*/ |
|
58 |
service.interceptors.response.use((response) => { |
|
59 |
if (response.request.responseType === 'blob') { |
|
60 |
return response |
|
61 |
} |
|
62 |
const resData = response.data |
|
63 |
const code = response.data.code |
|
64 |
if (!store.state.app.hasError) { |
|
65 |
if (code === 1011006 || code === 1011007 || code === 1011008 || code === 1011009) { |
|
66 |
Modal.error({ |
|
67 |
title: '提示:', |
|
68 |
content: resData.message, |
|
69 |
okText: '重新登录', |
|
70 |
onOk: () => { |
|
71 |
Vue.ls.remove(ACCESS_TOKEN) |
|
72 |
store.dispatch('SetHasError', false) |
|
73 |
window.location.reload() |
|
74 |
} |
|
75 |
}) |
|
76 |
store.dispatch('SetHasError', true) |
|
77 |
} |
|
78 |
if (code === 1013002 || code === 1016002 || code === 1015002) { |
|
79 |
message.error(response.data.message) |
|
80 |
return response.data |
|
81 |
} |
|
82 |
} |
|
83 |
return resData |
|
84 |
}, err) |
|
85 |
|
|
86 |
const installer = { |
|
87 |
vm: {}, |
|
88 |
install (Vue) { |
|
89 |
Vue.use(VueAxios, service) |
|
90 |
} |
|
91 |
} |
|
92 |
|
|
93 |
export { |
|
94 |
installer as VueAxios, |
|
95 |
service as axios |
|
96 |
} |