Files
ai_game/client/js/utils/http.js

116 lines
2.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* 网络请求工具 - 支持本地/云托管切换
*/
// ============================================
// 环境配置(切换这里即可)
// ============================================
const ENV = 'cloud'; // 'local' = 本地后端, 'cloud' = 微信云托管
const CONFIG = {
local: {
baseUrl: 'http://localhost:8000/api'
},
cloud: {
env: 'prod-6gjx1rd4c40f5884',
serviceName: 'express-fuvd'
}
};
/**
* 发送HTTP请求
*/
export function request(options) {
if (ENV === 'local') {
return requestLocal(options);
} else {
return requestCloud(options);
}
}
/**
* 本地后端请求wx.request
*/
function requestLocal(options) {
return new Promise((resolve, reject) => {
wx.request({
url: CONFIG.local.baseUrl + options.url,
method: options.method || 'GET',
data: options.data || {},
timeout: options.timeout || 30000,
header: {
'Content-Type': 'application/json',
...options.header
},
success(res) {
if (res.data && res.data.code === 0) {
resolve(res.data.data);
} else {
reject(new Error(res.data?.message || '请求失败'));
}
},
fail(err) {
console.error('[HTTP-Local] 请求失败:', err);
reject(err);
}
});
});
}
/**
* 云托管请求wx.cloud.callContainer
*/
function requestCloud(options) {
return new Promise((resolve, reject) => {
wx.cloud.callContainer({
config: {
env: CONFIG.cloud.env
},
path: '/api' + options.url,
method: options.method || 'GET',
data: options.data || {},
header: {
'X-WX-SERVICE': CONFIG.cloud.serviceName,
'Content-Type': 'application/json',
...options.header
},
success(res) {
if (res.data && res.data.code === 0) {
resolve(res.data.data);
} else if (res.data) {
reject(new Error(res.data.message || '请求失败'));
} else {
reject(new Error('响应数据异常'));
}
},
fail(err) {
console.error('[HTTP-Cloud] 请求失败:', err);
reject(err);
}
});
});
}
/**
* GET请求
*/
export function get(url, data) {
return request({ url, method: 'GET', data });
}
/**
* POST请求
*/
export function post(url, data, options = {}) {
return request({ url, method: 'POST', data, ...options });
}
/**
* DELETE请求
*/
export function del(url, data) {
return request({ url, method: 'DELETE', data });
}
export default { request, get, post, del };