otpm/miniprogram-example/utils/request.js
“xHuPo” 44500afd3f beta
2025-05-23 19:09:06 +08:00

58 lines
No EOL
1.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// 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) {
wx.removeStorageSync('token');
wx.removeStorageSync('openid');
reject(new Error('登录已过期,请重新登录'));
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;