axios.js
3.1 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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
import axios from 'axios'
import router from '@/router'
import store from '@/store'
import { Notify } from 'vant'
import { setToken, getToken } from '@/libs/util'
const addErrorLog = errorInfo => {
const { statusText, status, config } = errorInfo
let info = {
type: 'ajax',
code: status,
// osInfo: getOs(),
// browserInfo: getBrowser().browser + '/' + getBrowser().version,
msg: errorInfo.data.message ? errorInfo.data.message : statusText,
url: config.url,
dataInfo: config.data ? JSON.parse(config.data) : {},
headers: config.headers
}
if (!config.url.includes('save_error_logger')) {
store.dispatch('addErrorLog', info)
}
}
class HttpRequest {
path = ''
curPath = ''
constructor(baseUrl = baseURL) {
this.baseUrl = baseUrl
this.queue = {}
}
getInsideConfig() {
const config = {
baseURL: this.baseUrl,
headers: {}
}
if (getToken()) {
config.headers.Authorization = 'Bearer ' + getToken()
}
return config
}
destroy(url) {
delete this.queue[url]
if (!Object.keys(this.queue).length) {
// Spin.hide()
}
}
interceptors(instance, url) {
// 请求拦截
instance.interceptors.request.use(
config => {
// 添加全局的loading...
// if (!Object.keys(this.queue).length) {
// Spin.show() // 不建议开启,因为界面不友好
// }
this.queue[url] = true
return config
},
error => {
return Promise.reject(error)
}
)
// 响应拦截
instance.interceptors.response.use(
response => {
this.destroy(url)
// console.log(response)
if (response.data.code == 200) {
return response.data
} else {
Notify({ type: 'warning', message: response.data.message })
return Promise.reject(response.data.message)
}
},
error => {
this.destroy(url)
let errorInfo = error.response
console.log('errorInfo:', errorInfo)
if (!errorInfo) {
const {
request: { statusText, status },
config
} = JSON.parse(JSON.stringify(error))
console.log('config:', config)
errorInfo = {
statusText,
status,
config
}
}
addErrorLog(errorInfo)
if (errorInfo.status === 401) {
setToken('')
router.replace({
name: 'login'
})
}
return Promise.reject(error)
}
)
}
setPath(...paths) {
this.curPath = `${this.path}/${paths.join('/')}`
return this
}
replace(...params) {
let count = 0
this.curPath = this.curPath.replace(/\{.*?\}/g, _match => params[count++])
return this
}
request(options) {
const instance = axios.create()
options = Object.assign(this.getInsideConfig(), options)
if (this.curPath !== '') {
options.url = this.curPath
this.curPath = ''
this.path = ''
}
this.interceptors(instance, options.url)
return instance(options)
}
}
export default HttpRequest