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
/**
* 基础请求方法
*/
import axios from 'axios'
import { showFailToast, showLoadingToast } from 'vant'
const baseAxios = axios.create({
baseURL: '',
timeout: 20000,
})
// 加载标志计数
let loadingList = 0
let loadingToast = null
let errorMark = 0
export function fetchBase({
url = '',
// 需要携带在url上的参数
params,
// 请求体body的参数
body = {},
method = 'POST',
contentType = 'json',
loading = false
} = {}) {
contentType === 'form' && (contentType = 'application/x-www-form-urlencoded')
contentType === 'json' && (contentType = 'application/json; charset=utf-8')
contentType === 'file' && (contentType = 'multipart/form-data')
return new Promise((resolve, reject) => {
if (loading) {
loadingList++
loadingToast = showLoadingToast({ message: '请求中', forbidClick: true, duration: 0 })
}
baseAxios({
method: method,
url: `${url}`,
params: params,
data: body,
headers: {
'Content-Type': contentType
}
}).then(function (response) {
const data = response.data || {}
if (data.code !== 'SUCCESS') {
errorMark++
reject(data)
return
}
resolve(data)
}).catch(function (err) {
errorMark++
reject(err)
}).finally(() => {
if (loading) {
loadingList--
if (loadingList <= 0 && loadingToast) {
loadingToast.close()
loadingToast = null
}
}
if (errorMark) {
setTimeout(() => {
showFailToast('请求失败')
}, 300)
errorMark = 0
}
})
})
}