request.js
2.96 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
97
98
99
100
101
102
103
104
105
106
107
108
import base from "@/config/baseUrl";
import store from "@/store";
import {
judgeLogin
} from "@/config/login";
// 初始化请求配置
uni.$u.http.setConfig((config) => {
const token =
store.state.userInfo.isToken ||
uni.getStorageSync("userInfo").isToken ||
undefined;
// #ifdef H5
window.sessionStorage.getItem("userInfo").isToken;
// #endif
/* config 为默认全局配置*/
config.baseURL = base.baseUrl; /* 根域名 */
config.header = {
"Content-Type": "application/json",
'X-Authorization': "Bearer " + token,
};
config.custom = {
load: true, //是否显示加载动画
isFactory: true, //true:返回的数据成功只返回data false:返回response
catch: true, //默认数据返回不成功进入catch返回
auth: true, //token
};
return config;
});
// 请求拦截
uni.$u.http.interceptors.request.use(
(config) => {
if (store.state.userInfo.isThirdLogin) {
uni.switchTab({
url: "../pages/personal/personal",
});
}
// 初始化请求拦截器时,会执行此方法,此时data为undefined,赋予默认{}
config.data = config.data || {};
// 根据custom参数中配置的是否需要token,添加对应的请求头
if (config?.custom?.auth) {
config.header['X-Authorization'] =
"Bearer " + store.state.userInfo.isToken ||
uni.getStorageSync("userInfo").isToken ||
undefined;
}
if (config?.custom?.load) {
//打开加载动画
store.commit("setLoadingShow", true);
}
return config;
},
(config) => {
return Promise.reject(config);
}
);
// 响应拦截
uni.$u.http.interceptors.response.use(
(response) => {
// 关闭加载动画
store.commit("setLoadingShow", false);
const data = response.data;
const custom = response.config?.custom;
// code: 200、请求成功 其他,没有更多参数 401、被迫下线重新登录、
if (response.statusCode == 200) {
return Promise.resolve(data);
} else if (response.statusCode == 401) {
// 清空登录信息
store.commit("emptyUserInfo");
// 20秒节流,弹窗登录
uni.$u.throttle(judgeLogin(), 20000);
return new Promise(() => {});
} else {}
},
(response) => {
// 关闭加载动画
store.commit("setLoadingShow", false);
let show = true;
let errorData = '请检查网络或服务器'
let message = response.data?.message || response?.errMsg;
if (message == "request:fail url not in domain list") {
errorData = "检查请求域名是否添加了域名白名单";
} else if (message == "request:fail timeout") {
errorData = "请求超时:请检查网络";
} else if (response.data.status == 401) {
if (!store.state.userInfo.isThirdLogin) {
uni.reLaunch({
url: "/publicLoginSubPage/public/login",
});
// 清空登录信息
store.commit("emptyUserInfo");
show = false;
} else {
uni.switchTab({
url: "../pages/personal/personal",
});
show = false;
}
} else {
errorData = message || "";
}
if (show) uni.$u.toast(errorData);
return Promise.reject(response);
}
);