This commit is contained in:
2025-12-05 15:41:32 +08:00
commit 7339c71fc0
1433 changed files with 37574 additions and 0 deletions

157
utils/request.js Normal file
View File

@@ -0,0 +1,157 @@
// utils/request.js - 网络请求封装
const app = getApp();
// 请求配置
const config = {
timeout: 10000,
header: {
'Content-Type': 'application/json'
}
};
/**
* 封装的请求方法
* @param {Object} options - 请求选项
* @param {string} options.url - 请求地址
* @param {string} options.method - 请求方法
* @param {Object} options.data - 请求数据
* @param {Object} options.header - 请求头
* @param {boolean} options.showLoading - 是否显示loading
* @param {string} options.loadingText - loading文字
*/
const request = (options) => {
return new Promise((resolve, reject) => {
const {
url,
method = 'GET',
data = {},
header = {},
showLoading = true,
loadingText = '加载中...'
} = options;
// 显示loading
if (showLoading) {
wx.showLoading({
title: loadingText,
mask: true
});
}
// 合并请求头
const requestHeader = {
...config.header,
...header
};
// 添加token
if (app.globalData.token) {
requestHeader['Authorization'] = `Bearer ${app.globalData.token}`;
}
// 拼接完整URL
const fullUrl = url.startsWith('http') ? url : `${app.globalData.baseUrl}${url}`;
wx.request({
url: fullUrl,
method,
data,
header: requestHeader,
timeout: config.timeout,
success: (res) => {
if (showLoading) {
wx.hideLoading();
}
const { statusCode, data: responseData } = res;
// HTTP状态码判断
if (statusCode >= 200 && statusCode < 300) {
// 业务状态码判断(根据实际接口调整)
if (responseData.code === 0 || responseData.code === 200) {
resolve(responseData);
} else if (responseData.code === 401) {
// token过期清除登录状态
app.clearToken();
wx.showToast({
title: '登录已过期,请重新登录',
icon: 'none'
});
reject(responseData);
} else {
wx.showToast({
title: responseData.message || '请求失败',
icon: 'none'
});
reject(responseData);
}
} else {
wx.showToast({
title: `请求失败(${statusCode})`,
icon: 'none'
});
reject(res);
}
},
fail: (err) => {
if (showLoading) {
wx.hideLoading();
}
wx.showToast({
title: '网络请求失败',
icon: 'none'
});
reject(err);
}
});
});
};
// GET请求
const get = (url, data = {}, options = {}) => {
return request({
url,
method: 'GET',
data,
...options
});
};
// POST请求
const post = (url, data = {}, options = {}) => {
return request({
url,
method: 'POST',
data,
...options
});
};
// PUT请求
const put = (url, data = {}, options = {}) => {
return request({
url,
method: 'PUT',
data,
...options
});
};
// DELETE请求
const del = (url, data = {}, options = {}) => {
return request({
url,
method: 'DELETE',
data,
...options
});
};
module.exports = {
request,
get,
post,
put,
del
};