236 lines
6.1 KiB
JavaScript
236 lines
6.1 KiB
JavaScript
// utils/request.js - 微信小程序网络请求封装
|
|
|
|
const app = getApp();
|
|
|
|
const { config } = require('../config');
|
|
const API_BASE_URL = config.apiBaseUrl;
|
|
|
|
// 将 snake_case 转换为 camelCase
|
|
const toCamelCase = (str) => {
|
|
return str.replace(/_([a-z])/g, (_, letter) => letter.toUpperCase());
|
|
};
|
|
|
|
// 递归转换对象的所有 key 为 camelCase
|
|
const transformKeysToCamelCase = (obj) => {
|
|
if (obj === null || obj === undefined) {
|
|
return obj;
|
|
}
|
|
|
|
if (Array.isArray(obj)) {
|
|
return obj.map(transformKeysToCamelCase);
|
|
}
|
|
|
|
if (typeof obj === 'object' && obj.constructor === Object) {
|
|
const transformed = {};
|
|
for (const key in obj) {
|
|
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
|
transformed[toCamelCase(key)] = transformKeysToCamelCase(obj[key]);
|
|
}
|
|
}
|
|
return transformed;
|
|
}
|
|
|
|
return obj;
|
|
};
|
|
|
|
// 将 camelCase 转换为 snake_case
|
|
const toSnakeCase = (str) => {
|
|
return str.replace(/[A-Z]/g, (letter) => `_${letter.toLowerCase()}`);
|
|
};
|
|
|
|
// 递归转换对象的 key 为 snake_case
|
|
const transformKeysToSnakeCase = (obj) => {
|
|
if (obj === null || obj === undefined) {
|
|
return obj;
|
|
}
|
|
|
|
if (Array.isArray(obj)) {
|
|
return obj.map(transformKeysToSnakeCase);
|
|
}
|
|
|
|
if (typeof obj === 'object' && obj.constructor === Object) {
|
|
const transformed = {};
|
|
for (const key in obj) {
|
|
if (Object.prototype.hasOwnProperty.call(obj, key)) {
|
|
transformed[toSnakeCase(key)] = transformKeysToSnakeCase(obj[key]);
|
|
}
|
|
}
|
|
return transformed;
|
|
}
|
|
|
|
return obj;
|
|
};
|
|
|
|
/**
|
|
* 发起网络请求
|
|
* @param {string} url - 请求地址
|
|
* @param {string} method - 请求方法
|
|
* @param {object} data - 请求数据
|
|
* @param {object} options - 其他选项
|
|
*/
|
|
const request = (url, method = 'GET', data = {}, options = {}) => {
|
|
const {
|
|
showLoading = true,
|
|
loadingText = '加载中...',
|
|
showError = true,
|
|
} = options;
|
|
|
|
return new Promise((resolve, reject) => {
|
|
// 显示加载中
|
|
if (showLoading) {
|
|
wx.showLoading({
|
|
title: loadingText,
|
|
mask: true,
|
|
});
|
|
}
|
|
|
|
const token = wx.getStorageSync('token');
|
|
const userId = wx.getStorageSync('userId');
|
|
|
|
const header = {
|
|
'Content-Type': 'application/json; charset=utf-8',
|
|
...options.header,
|
|
};
|
|
|
|
if (token) {
|
|
header['Authorization'] = `Bearer ${token}`;
|
|
}
|
|
if (userId) {
|
|
header['x-user-id'] = userId;
|
|
}
|
|
|
|
// 转换请求数据 key 为 snake_case
|
|
const requestData = transformKeysToSnakeCase(data);
|
|
|
|
// 显式 JSON.stringify 避免小程序自动序列化时的编码问题
|
|
const jsonData = JSON.stringify(requestData);
|
|
|
|
wx.request({
|
|
url: `${API_BASE_URL}${url}`,
|
|
method,
|
|
data: jsonData,
|
|
header,
|
|
timeout: options.timeout || 10000,
|
|
success: (res) => {
|
|
if (showLoading) {
|
|
wx.hideLoading();
|
|
}
|
|
|
|
if (res.statusCode === 200) {
|
|
// 转换响应数据 key 为 camelCase
|
|
const transformedData = transformKeysToCamelCase(res.data);
|
|
resolve(transformedData);
|
|
} else if (res.statusCode === 401) {
|
|
// 未授权:静默清除登录状态,不强制跳转登录页,由用户后续操作时自主选择登录
|
|
app.clearLoginInfo();
|
|
wx.removeStorageSync('token');
|
|
wx.removeStorageSync('userId');
|
|
wx.removeStorageSync('isLoggedIn');
|
|
reject({ message: '登录已过期,请重新登录', silent: true });
|
|
} else {
|
|
if (showError) {
|
|
wx.showToast({
|
|
title: res.data?.message || '请求失败',
|
|
icon: 'none',
|
|
});
|
|
}
|
|
reject(res.data || { message: '请求失败' });
|
|
}
|
|
},
|
|
fail: (err) => {
|
|
if (showLoading) {
|
|
wx.hideLoading();
|
|
}
|
|
|
|
if (showError) {
|
|
wx.showToast({
|
|
title: err.errMsg || '网络错误',
|
|
icon: 'none',
|
|
});
|
|
}
|
|
reject(err);
|
|
},
|
|
});
|
|
});
|
|
};
|
|
|
|
// 封装常用请求方法
|
|
const get = (url, data, options) => request(url, 'GET', data, options);
|
|
const post = (url, data, options) => request(url, 'POST', data, options);
|
|
const put = (url, data, options) => request(url, 'PUT', data, options);
|
|
const del = (url, data, options) => request(url, 'DELETE', data, options);
|
|
|
|
/**
|
|
* 上传文件
|
|
* @param {string} url - 上传地址
|
|
* @param {string} filePath - 文件路径
|
|
* @param {string} name - 文件对应的 key
|
|
* @param {object} formData - 其他表单数据
|
|
*/
|
|
const uploadFile = (url, filePath, name = 'file', formData = {}) => {
|
|
return new Promise((resolve, reject) => {
|
|
wx.showLoading({
|
|
title: '上传中...',
|
|
mask: true,
|
|
});
|
|
|
|
const token = wx.getStorageSync('token');
|
|
const userId = wx.getStorageSync('userId');
|
|
|
|
const header = {};
|
|
if (token) {
|
|
header['Authorization'] = `Bearer ${token}`;
|
|
}
|
|
if (userId) {
|
|
header['x-user-id'] = userId;
|
|
}
|
|
|
|
wx.uploadFile({
|
|
url: `${API_BASE_URL}${url}`,
|
|
filePath,
|
|
name,
|
|
formData: transformKeysToSnakeCase(formData),
|
|
header,
|
|
timeout: 30000,
|
|
success: (res) => {
|
|
wx.hideLoading();
|
|
if (res.statusCode === 200) {
|
|
try {
|
|
const data = JSON.parse(res.data);
|
|
resolve(transformKeysToCamelCase(data));
|
|
} catch (e) {
|
|
console.error('上传响应解析失败:', res.data);
|
|
wx.showToast({ title: '上传失败', icon: 'none' });
|
|
reject({ message: '上传失败' });
|
|
}
|
|
} else {
|
|
console.error('上传返回非200:', res.statusCode, res.data);
|
|
wx.showToast({
|
|
title: '上传失败',
|
|
icon: 'none',
|
|
});
|
|
reject({ message: '上传失败' });
|
|
}
|
|
},
|
|
fail: (err) => {
|
|
wx.hideLoading();
|
|
console.error('wx.uploadFile fail:', JSON.stringify(err));
|
|
wx.showToast({
|
|
title: err.errMsg || '上传失败',
|
|
icon: 'none',
|
|
});
|
|
reject(err);
|
|
},
|
|
});
|
|
});
|
|
};
|
|
|
|
module.exports = {
|
|
request,
|
|
get,
|
|
post,
|
|
put,
|
|
del,
|
|
uploadFile,
|
|
};
|