interceptors.js
2.7 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
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
import { http, toast} from '@/uni_modules/uview-plus'
import useUserStore from '@/store/modules/user.js'
import errorCode from './errorCode';
const requestInterceptors=(vm)=>{
/**
* 请求拦截
* @param {Object} http
*/
http.interceptors.request.use((config) => { // 可使用async await 做异步操作
// 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
config.data = config.data || {}
// 根据custom参数中配置的是否需要token,添加对应的请求头
if(config?.custom?.auth) {
const userStore = useUserStore()
// 可以在此通过vm引用vuex中的变量,具体值在vm.$store.state中
config.header.Authorization = userStore.token
}
// console.log(config)
return config
}, (config) => // 可使用async await 做异步操作
Promise.reject(config))
}
// 当前是否显示modal
let loginModal = false
const responseInterceptors=(vm)=>{
/**
* 响应拦截
* @param {Object} http
*/
http.interceptors.response.use((response) => { /* 对响应成功做点什么 可使用async await 做异步操作*/
const data = response.data
// 未设置状态码则默认成功状态
const code = response.data.code || 200;
const msg = errorCode[code] || response.data.msg || errorCode['default']
if(data.code === 401 ) {
// 判断是否为用户
const userStore = useUserStore()
if(userStore.roleGroup === '普通角色'){
uni.login({
success: async (loginRes) => {
await userStore.login({code: loginRes.code, type: 0})
uni.switchTab({
url: '/pages/index/index'
})
}
});
}else {
// 防止重复弹窗
if (!loginModal) {
loginModal = true
// 弹窗告诉用户去登录
uni.showModal({
title: '温馨提示',
content: '你的身份信息已过期,需要重新登录~',
// showCancel: false,
confirmText: "前往登录",
cancelText: "暂不登录",
success: res => {
if (res.confirm) {
uni.navigateTo({
url: '/pages/login/login'
})
}
if (res.cancel) {
}
loginModal = false
}
})
}
}
} else if (code === 500) {
uni.$u.toast(`${msg}`)
return Promise.reject(new Error(msg))
} else if (code === 601) {
uni.$u.toast(`${msg}`)
return Promise.reject(new Error(msg))
} else if (code !== 200) {
uni.$u.toast(`${msg}`)
return Promise.reject('error')
} else {
return Promise.resolve(data)
}
}, (response) => { /* 对响应错误做点什么 (statusCode !== 200)*/
let { msg } = response.data
uni.$u.toast(`${msg}`)
return Promise.reject(response)
})
}
export {
requestInterceptors,
responseInterceptors
}