|
@@ -0,0 +1,60 @@
|
|
1
|
+import axios from 'axios'
|
|
2
|
+import { Toast } from 'vant'
|
|
3
|
+import qs from 'qs'
|
|
4
|
+
|
|
5
|
+const Axios = axios.create({
|
|
6
|
+ timeout: 60000,
|
|
7
|
+ responseType: 'json',
|
|
8
|
+ withCredentials: true,
|
|
9
|
+ headers: {}
|
|
10
|
+})
|
|
11
|
+
|
|
12
|
+Axios.interceptors.request.use((config) => {
|
|
13
|
+ Toast.loading({
|
|
14
|
+ duration: 0, // 持续展示 toast
|
|
15
|
+ forbidClick: true, // 禁用背景点击
|
|
16
|
+ loadingType: 'spinner',
|
|
17
|
+ color: 'white',
|
|
18
|
+ message: '请求中'
|
|
19
|
+ })
|
|
20
|
+ // 处理请求data,若为get请求,拼到url后面,若为post请求,直接添加到body中
|
|
21
|
+ let data = qs.stringify(config.data)
|
|
22
|
+ if (config.method === 'get' || config.method === 'GET') {
|
|
23
|
+ // 判断是通过斜杠传参还是通过query传参
|
|
24
|
+ if (config.url.indexOf(':') > -1) {
|
|
25
|
+ if (typeof config.data === 'object') {
|
|
26
|
+ config.url = Object.keys(config.data).reduce((url, k) => { // 此方法对每个元素进行处理
|
|
27
|
+ const re = new RegExp(`:${k}(?!w)`, 'i')
|
|
28
|
+ return url.replace(re, config.data[k])
|
|
29
|
+ }, config.url)
|
|
30
|
+ } else {
|
|
31
|
+ config.url = config.url.slice(0, config.url.indexOf(':')) + data
|
|
32
|
+ }
|
|
33
|
+ } else {
|
|
34
|
+ config.url += '?' + data
|
|
35
|
+ }
|
|
36
|
+ }
|
|
37
|
+ return config
|
|
38
|
+}, (error) => {
|
|
39
|
+ console.log(error)
|
|
40
|
+})
|
|
41
|
+
|
|
42
|
+Axios.interceptors.response.use((res) => {
|
|
43
|
+ setTimeout(() => {
|
|
44
|
+ Toast.clear()
|
|
45
|
+ }, 500)
|
|
46
|
+ if (res.status === 200) {
|
|
47
|
+ return res.data
|
|
48
|
+ } else {
|
|
49
|
+ Toast.fail('请求失败,状态码为' + res.status)
|
|
50
|
+ return res.data
|
|
51
|
+ }
|
|
52
|
+}, (error) => {
|
|
53
|
+ Toast.fail('请求失败,服务器异常')
|
|
54
|
+ setTimeout(() => {
|
|
55
|
+ Toast.clear()
|
|
56
|
+ }, 500)
|
|
57
|
+ console.log(error)
|
|
58
|
+})
|
|
59
|
+
|
|
60
|
+export default Axios
|