request.js
1.44 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
import http from '@/components/common/tui-request'
import { APICodeEnum } from '@/utils/enum'
import { baseURL, version } from '@/config/app'
import { useCounterStore } from '@/stores/counter'
function checkParams(params) {
if (typeof params != 'object') return params;
for (let key in params) {
const value = params[key]
if (value === null || value === undefined || value === "") {
delete params[key]
}
}
return params
}
const events = {
// 成功
success(data) {
return Promise.resolve(data)
},
// 失败
fail({msg}) {
uni.showToast({title: msg, icon: 'none'})
return Promise.reject(msg)
},
// 重定向到登录
redirect({msg}) {
useCounterStore().loginOut()
uni.redirectTo({url: '/pages/login'})
return Promise.reject(msg)
}
}
//初始化请求配置项
http.create({
host: baseURL + '/ylapi/yuanl',
// host: baseURL + '/yuanl/yuanl',
header: {'content-type': 'application/json', 'version': version},
timeout: 30000,
showLoading: false
})
//请求拦截
http.interceptors.request.use(config => {
const useCounter = useCounterStore()
// 清除空的字段
config.data = checkParams(config.data)
// 请求头token
if(useCounter.userToken){
config.header = {'Authorization': useCounter.userToken}
}
return config
})
//响应拦截
http.interceptors.response.use(response => {
var { code,msg } = response.data
if (code!=401 && code!=200) code = 500
return events[APICodeEnum[code]](response.data)
})
export default http