request.js
3.29 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
import config from '@/config/index.js';
import store from '@/store/index.js';
const apiHost = config.apiHost;
const env = config.env;
const systemInfo = wx.getSystemInfoSync();
// 此vm参数为页面的实例,可以通过它引用vuex中的变量
module.exports = vm => {
// 初始化请求配置
uni.$u.http.setConfig(config => {
/* config 为默认全局配置*/
config.baseURL = apiHost; /* 根域名 */
config.header = {
'content-type': 'application/json;charset=UTF-8',
deviceName: systemInfo.brand, // 设备品牌
deviceModel: systemInfo.model, // 设备型号
systemType: systemInfo.platform, // 操作系统类型
systemVersion: systemInfo.system, // 操作系统版本
wechatVersion: systemInfo.version, // 微信版本
SDKVersion: systemInfo.SDKVersion, // 基础库版本
platform: 'mp', // 当前运行平台
env: env, //环境
};
return config;
});
// 请求拦截
uni.$u.http.interceptors.request.use(
config => {
// 可使用async await 做异步操作
if (config.custom.auth === false) {
delete config.header['Authorization'];
} else {
config.header['Authorization'] = `Bearer ${vm.$store.state?.userInfo?.accessToken}`;
}
// config.header['Authorization'] = `Bearer 814aec36-60b1-4b47-a0fa-b909501f3e48`;
return config;
},
config => {
// 可使用async await 做异步操作
return Promise.reject(config);
},
);
// 响应拦截
uni.$u.http.interceptors.response.use(
response => {
const { data = {}, statusCode, config } = response;
const { success, message = '', businessException, errorCode } = data;
if (config && config.interceptors === false) {
// 请求配置不做返回拦截的情况
return response;
} else {
if (success) {
return data;
} else {
if (`${errorCode}` === '401') {
console.error(`【${errorCode}】登录过期`);
store.commit('SET_AUTHED', false);
setTimeout(() => {
uni.reLaunch({ url: '/pages/login/login' });
}, 200);
return Promise.reject(message);
}
if (businessException && !(config && config.custom && config.custom.toast)) {
uni.showToast({ icon: 'none', title: message || `[${errorCode}]系统异常`, duration: 3000 });
} else if (!(config && config.custom && config.custom.toast)) {
if (config.toast !== false) {
if (`${errorCode}`.substr(0, 1) === '5') {
uni.showToast({ icon: 'none', title: `[${errorCode}]系统异常`, duration: 3000 });
} else {
uni.showToast({ icon: 'none', title: message || `[${errorCode}]系统异常`, duration: 3000 });
}
}
}
return Promise.reject(message);
}
}
},
response => {
// 对响应错误做点什么 (statusCode !== 200)
const { statusCode } = response;
if (statusCode === 401) {
console.error(`【${statusCode}】登录过期`);
store.commit('SET_AUTHED', false);
setTimeout(() => {
uni.reLaunch({ url: '/pages/login/login' });
}, 1200);
}
return Promise.reject(response);
},
);
};