This commit is contained in:
sjk
2025-11-17 14:11:46 +08:00
commit ad4a600af9
1659 changed files with 171560 additions and 0 deletions

View File

@@ -0,0 +1,120 @@
import { config } from '../../config/index';
/**
* 网络请求工具函数
* @param {Object} options 请求配置
* @param {string} options.url 请求地址
* @param {string} options.method 请求方法
* @param {Object} options.data 请求数据
* @param {Object} options.header 请求头
*/
export function request(options) {
const { url, method = 'GET', data = {}, header = {} } = options;
// 构建完整的请求URL
const fullUrl = `${config.apiBase}${url}`;
// 获取token
const token = wx.getStorageSync('token');
// 设置默认请求头
const defaultHeader = {
'Content-Type': 'application/json',
...header
};
// 如果有token添加到请求头
if (token) {
defaultHeader['Authorization'] = `Bearer ${token}`;
}
return new Promise((resolve, reject) => {
wx.request({
url: fullUrl,
method: method.toUpperCase(),
data: data,
header: defaultHeader,
success: (res) => {
console.log(`API请求成功: ${method.toUpperCase()} ${fullUrl}`, res);
if (res.statusCode === 200) {
// 检查业务状态码
if (res.data && res.data.code === 200) {
resolve(res.data);
} else {
// 业务错误
const errorMsg = res.data?.message || '请求失败';
console.error('API业务错误:', errorMsg);
reject(new Error(errorMsg));
}
} else if (res.statusCode === 401) {
// 未授权清除token并跳转到登录页
wx.removeStorageSync('token');
wx.showToast({
title: '请先登录',
icon: 'none'
});
setTimeout(() => {
wx.navigateTo({
url: '/pages/login/index'
});
}, 1500);
reject(new Error('未授权'));
} else {
// HTTP错误
const errorMsg = `请求失败: ${res.statusCode}`;
console.error('API HTTP错误:', errorMsg);
reject(new Error(errorMsg));
}
},
fail: (error) => {
console.error(`API请求失败: ${method.toUpperCase()} ${fullUrl}`, error);
// 网络错误处理
let errorMsg = '网络请求失败';
if (error.errMsg) {
if (error.errMsg.includes('timeout')) {
errorMsg = '请求超时,请检查网络连接';
} else if (error.errMsg.includes('fail')) {
errorMsg = '网络连接失败,请检查网络设置';
}
}
wx.showToast({
title: errorMsg,
icon: 'none'
});
reject(new Error(errorMsg));
}
});
});
}
/**
* GET请求
*/
export function get(url, data = {}, header = {}) {
return request({ url, method: 'GET', data, header });
}
/**
* POST请求
*/
export function post(url, data = {}, header = {}) {
return request({ url, method: 'POST', data, header });
}
/**
* PUT请求
*/
export function put(url, data = {}, header = {}) {
return request({ url, method: 'PUT', data, header });
}
/**
* DELETE请求
*/
export function del(url, data = {}, header = {}) {
return request({ url, method: 'DELETE', data, header });
}