You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

118 lines
3.3 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// utils/request.js
const { getAuthHeader, clearAuthData } = require('./token');
const BASE_URL = 'http://localhost:3000'; // 替换为你的后端接口域名
/**
* 封装 wx.request
* @param {Object} options - 请求配置
* @param {string} options.url - 接口路径(不包含域名)
* @param {string} [options.method='GET'] - 请求方法
* @param {Object} [options.data] - 请求参数
* @param {boolean} [options.showLoading=true] - 是否显示加载提示
* @param {string} [options.loadingText='加载中...'] - 加载提示文字
*/
const request = (options) => {
const {
url,
method = 'GET',
data = {},
showLoading = true,
loadingText = '加载中...'
} = options;
return new Promise((resolve, reject) => {
let loadingHide = () => {};
// 显示 loading
if (showLoading) {
wx.showLoading({
title: loadingText,
mask: true
});
loadingHide = wx.hideLoading;
}
wx.request({
url: BASE_URL + url,
method,
data,
header: getAuthHeader(),
success: (res) => {
const { statusCode, data: responseData } = res;
if (statusCode === 200) {
// 假设后端返回格式:{ code: 200, data: {}, msg: 'success' }
if (responseData.code === 200) {
resolve(responseData.data);
} else {
// 特殊处理401未授权错误
if (responseData.code === 401 || statusCode === 401) {
// token可能已过期清除本地认证信息
clearAuthData();
wx.showToast({
title: '登录已过期,请重新登录',
icon: 'none'
});
// 跳转到登录页
setTimeout(() => {
wx.redirectTo({
url: '/pages/login/login'
});
}, 1500);
reject(responseData);
} else {
// 其他业务错误(如参数错误等)
wx.showToast({
title: responseData.msg || '请求失败',
icon: 'none'
});
reject(responseData);
}
}
} else {
// HTTP 状态码非 200
if (statusCode === 401) {
// token可能已过期清除本地认证信息
clearAuthData();
wx.showToast({
title: '登录已过期,请重新登录',
icon: 'none'
});
// 跳转到登录页
setTimeout(() => {
wx.redirectTo({
url: '/pages/login/login'
});
}, 1500);
} else {
// wx.showToast({
// title: `请求错误 ${statusCode}`,
// icon: 'none'
// });
}
reject(res);
}
},
fail: (err) => {
wx.showToast({
title: '网络异常,请稍后重试',
icon: 'none'
});
reject(err);
},
complete: () => {
// 隐藏 loading
loadingHide();
}
});
});
};
module.exports = {
request,
get: (url, data, options = {}) => request({ ...options, url, method: 'GET', data }),
post: (url, data, options = {}) => request({ ...options, url, method: 'POST', data })
};