responseInterceptors.js
2.0 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
/**
* 响应拦截
* @param {Object} http
*/
module.exports = (vm) => {
uni.$u.http.interceptors.response.use((response) => {
console.log(response);
/* 对响应成功做点什么 可使用async await 做异步操作*/
const statusCode = response.statusCode
const data = response.data
// 自定义参数
const custom = response.config?.custom
if (statusCode == 401) {
var prepath = getCurrentPage();
uni.setStorageSync('prepath', prepath);
uni.redirectTo({
url: '/pages/index/login'
});
return;
} else if (statusCode != 200 &&statusCode != 100) { // 服务端返回的状态码不等于200,则reject()
// 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
if (custom.toast !== false) {
uni.$u.toast(data.message || data.msg)
}
// 如果需要catch返回,则进行reject
if (custom?.catch) {
return Promise.reject(data)
} else {
// 否则返回一个pending中的promise
return new Promise(() => {})
}
}
return Promise.resolve(data || {})
}, (response) => {
/* 对响应错误做点什么 (statusCode !== 200)*/
switch (response.statusCode) {
case 401:
var prepath = getCurrentPage();
console.log(prepath);
uni.setStorageSync('prepath', prepath);
uni.redirectTo({
url: '/pages/index/login'
});
break;
default:
uni.$u.toast('请求失败')
break;
}
return Promise.reject(response)
})
}
const getCurrentPage = () => {
var pages = getCurrentPages() //获取加载的页面
var currentPage = pages[pages.length - 1] //获取当前页面的对象
var url = currentPage.route //当前页面url
var options = currentPage.options //如果要获取url中所带的参数可以查看options
//拼接url的参数
var urlWithArgs = url + '?'
for (var key in options) {
var value = options[key]
urlWithArgs += key + '=' + value + '&'
}
urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1);
wx.setStorageSync('perpath', urlWithArgs);
return urlWithArgs;
}