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
import axios from 'axios'
import { ElLoading } from 'element-plus'
const VERSION = '20210531'
const APP_VERSION = '' + VERSION.replace(/\"/g, '') // 当前应用版本
const API_VERSION = '0.0.5' // 当前API版本
const OS_VERSION = 'window10' // 当前操作操作系统版本
var loading: any
var hide_loading = false
/**
* 创建axios实例
*/
const request: any = axios.create({
baseURL: import.meta.env.MODE === 'production' ? '/' : '/api/', // api的base_url
timeout: 600000 // 请求超时时间
})
/** 下一次请求不显示Loading */
request.hideLoadingOnce = function () {
hide_loading = true
}
/**
* 是否隐藏Loading
*
* @returns
*/
function isHideLoading() {
var b = hide_loading
hide_loading = false
return b
}
/**
* 设置拦截器: 请求拦截器
*/
request.interceptors.request.use(
(config: any) => {
config.headers['tenant'] = '0'
if (!isHideLoading()) {
loading = ElLoading.service({ fullscreen: true })
}
config.headers['app-version'] = APP_VERSION
config.headers['api-version'] = API_VERSION
config.headers['os-version'] = OS_VERSION
let url = config.url!
// get参数编码
if (config.method === 'get' && config.params) {
url += '?'
const keys = Object.keys(config.params)
for (const key of keys) {
if (config.params[key] != null) {
url += `${key}=${encodeURIComponent(config.params[key])}&`
}
}
url = url.substring(0, url.length - 1)
config.params = {}
}
config.url = url
return config
},
(error: any) => {
loading && loading.close()
// Do something with request error
console.log(error) // for debug
Promise.reject(error)
}
)
/**
* 设置拦截器: 响应拦截器
*/
request.interceptors.response.use(
(response: any) => {
loading && loading.close()
const res = response.data
return res
},
(error: any) => {
loading && loading.close()
console.log(error)
if (error.response && error.response.data) {
try {
var data = error.response.data
if (typeof data === 'string') {
if (error.response.status === 503) {
data = {
code: -1,
message: '当前服务繁忙,请稍后再试!'
}
} else {
data = JSON.parse(error.response.data)
}
}
return Promise.reject(data)
} catch (e) {
return Promise.reject({
code: -1,
message: '网络异常: ' + error.response.data
})
}
} else {
return Promise.reject({
code: -1,
message: error
})
}
}
)
export default request