beta
This commit is contained in:
parent
a45ddf13d5
commit
bcd986e3f7
46 changed files with 6166 additions and 454 deletions
64
miniprogram-example/utils/request.js
Normal file
64
miniprogram-example/utils/request.js
Normal file
|
@ -0,0 +1,64 @@
|
|||
// request.js - 网络请求工具类
|
||||
|
||||
const BASE_URL = 'https://otpm.zeroc.net'; // 替换为实际的API域名
|
||||
|
||||
// 请求拦截器
|
||||
const request = (options) => {
|
||||
return new Promise((resolve, reject) => {
|
||||
const token = wx.getStorageSync('token');
|
||||
const header = {
|
||||
'Content-Type': 'application/json',
|
||||
...options.header
|
||||
};
|
||||
|
||||
// 如果有token,添加到请求头
|
||||
if (token) {
|
||||
header['Authorization'] = `Bearer ${token}`;
|
||||
}
|
||||
|
||||
wx.request({
|
||||
url: `${BASE_URL}${options.url}`,
|
||||
method: options.method || 'GET',
|
||||
data: options.data,
|
||||
header: header,
|
||||
success: (res) => {
|
||||
// 处理业务错误
|
||||
if (res.data.code !== 0) {
|
||||
// token过期,尝试刷新
|
||||
if (res.statusCode === 401) {
|
||||
refreshToken().then(() => {
|
||||
// 刷新token后重试请求
|
||||
request(options).then(resolve).catch(reject);
|
||||
}).catch((err) => {
|
||||
// 刷新失败,需要重新登录
|
||||
wx.removeStorageSync('token');
|
||||
wx.removeStorageSync('openid');
|
||||
reject(err);
|
||||
});
|
||||
return;
|
||||
}
|
||||
reject(new Error(res.data.message || '请求失败'));
|
||||
return;
|
||||
}
|
||||
resolve(res.data);
|
||||
},
|
||||
fail: reject
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
// 刷新token
|
||||
const refreshToken = () => {
|
||||
return request({
|
||||
url: '/refresh-token',
|
||||
method: 'POST'
|
||||
}).then(res => {
|
||||
if (res.data && res.data.token) {
|
||||
wx.setStorageSync('token', res.data.token);
|
||||
return res.data.token;
|
||||
}
|
||||
throw new Error('Failed to refresh token');
|
||||
});
|
||||
};
|
||||
|
||||
export default request;
|
Loading…
Add table
Add a link
Reference in a new issue