axios 封装及接口管理
utils/request.ts
封装 axios , 开发者需要根据后台接口做修改。
JSONbig
解决超过 16 位数字精度丢失问题config.loading
在接口里配置是否开启 loading 动画config.headers!.common['Authorization']
请求头携带 tokenservice.interceptors.response.use
接口响应处理 如 错误提示,重新登陆
javascript
import axios, { AxiosResponse, AxiosRequestConfig } from 'axios'
import JSONbig from 'json-bigint' //解决超过 16 位数字精度丢失问题
import { showToast, showLoadingToast, closeToast } from 'vant/lib/toast'
import { showDialog } from 'vant/lib/dialog'
import { useAppStore } from '@/store/app'
import router from '@/router/index'
export class StatusCode {
static SUCCESS = '200'
static ERROR = 400
static OUTDATE_TOKEN = 1001
}
const service = axios.create({
timeout: 6000,
transformResponse: [
(data) => {
try {
return JSON.parse(JSON.stringify(JSONbig.parse(data)))
} catch (err) {
return { data }
}
}
]
})
// Request interceptors
service.interceptors.request.use(
(config: AxiosRequestConfig) => {
// 加载动画
if (config.loading) {
showLoadingToast({
message: '加载中...',
forbidClick: true
})
}
const appStore = useAppStore()
if (appStore.token) {
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
config.headers!.common['Authorization'] = appStore.token
}
return config
},
(error: any) => {
Promise.reject(error)
}
)
// Response interceptors
service.interceptors.response.use(
async (response: AxiosResponse) => {
closeToast()
const res = response.data
if (res.code === StatusCode.SUCCESS) {
return response.data
} else {
if (res.code === StatusCode.OUTDATE_TOKEN) {
// token 失效
showDialog({
message: '登录失效,请重新登录',
theme: 'round-button'
}).then(() => {
router.replace('/')
})
return Promise.reject(res)
} else {
showToast(res.msg)
return Promise.reject(res)
}
}
},
(error: any) => {
showToast(error.response ? `请求异常${error.response.status}` : '网络超时,请刷新重试')
return Promise.reject(error)
}
)
export default service
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
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
使用
javascript
/**
* post请求
*/
export const fetchAuthCode = (data: AuthCode) => {
return (
request <
IResponseType >
{
url: envConfig.baseApi + "xxxxx",
method: "post",
data,
loading: true,
}
);
};
/**
* get请求
*/
export const fetchTagList = () => {
return (
request <
IResponseType >
{
url: envConfig.baseApi + "xxxxxx",
method: "get",
loading: false,
}
);
};
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
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