feat: 恢复http.js的Token认证和params处理功能

This commit is contained in:
wangwuww111
2026-03-11 22:50:53 +08:00
parent 4ac47c8474
commit e101e8721b

View File

@@ -5,11 +5,11 @@
// ============================================
// 环境配置(切换这里即可)
// ============================================
const ENV = 'cloud'; // 'local' = 本地后端, 'cloud' = 微信云托管
const ENV = 'local'; // 'local' = 本地后端, 'cloud' = 微信云托管
const CONFIG = {
local: {
baseUrl: 'http://localhost:8000/api'
baseUrl: 'http://localhost:8001/api'
},
cloud: {
env: 'prod-6gjx1rd4c40f5884',
@@ -17,6 +17,18 @@ const CONFIG = {
}
};
/**
* 获取存储的 Token
*/
function getToken() {
try {
const userInfo = wx.getStorageSync('userInfo');
return userInfo?.token || '';
} catch (e) {
return '';
}
}
/**
* 发送HTTP请求
*/
@@ -33,16 +45,39 @@ export function request(options) {
*/
function requestLocal(options) {
return new Promise((resolve, reject) => {
// 自动添加 Token 到请求头
const token = getToken();
const header = {
'Content-Type': 'application/json',
...options.header
};
if (token) {
header['Authorization'] = `Bearer ${token}`;
}
// 处理 URL 查询参数
let url = CONFIG.local.baseUrl + options.url;
if (options.params) {
const queryString = Object.entries(options.params)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
url += (url.includes('?') ? '&' : '?') + queryString;
}
wx.request({
url: CONFIG.local.baseUrl + options.url,
url,
method: options.method || 'GET',
data: options.data || {},
timeout: options.timeout || 30000,
header: {
'Content-Type': 'application/json',
...options.header
},
header,
success(res) {
// 处理 401 未授权错误
if (res.statusCode === 401) {
wx.removeStorageSync('userInfo');
reject(new Error('登录已过期,请重新登录'));
return;
}
if (res.data && res.data.code === 0) {
resolve(res.data.data);
} else {
@@ -62,19 +97,42 @@ function requestLocal(options) {
*/
function requestCloud(options) {
return new Promise((resolve, reject) => {
// 自动添加 Token 到请求头
const token = getToken();
const header = {
'X-WX-SERVICE': CONFIG.cloud.serviceName,
'Content-Type': 'application/json',
...options.header
};
if (token) {
header['Authorization'] = `Bearer ${token}`;
}
// 处理 URL 查询参数
let path = '/api' + options.url;
if (options.params) {
const queryString = Object.entries(options.params)
.map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(value)}`)
.join('&');
path += (path.includes('?') ? '&' : '?') + queryString;
}
wx.cloud.callContainer({
config: {
env: CONFIG.cloud.env
},
path: '/api' + options.url,
path,
method: options.method || 'GET',
data: options.data || {},
header: {
'X-WX-SERVICE': CONFIG.cloud.serviceName,
'Content-Type': 'application/json',
...options.header
},
header,
success(res) {
// 处理 401 未授权错误
if (res.statusCode === 401) {
wx.removeStorageSync('userInfo');
reject(new Error('登录已过期,请重新登录'));
return;
}
if (res.data && res.data.code === 0) {
resolve(res.data.data);
} else if (res.data) {