|
|
// 全局配置
|
|
|
const config = {
|
|
|
port: '48080' // 默认端口
|
|
|
};
|
|
|
|
|
|
// 动态更新配置
|
|
|
export function updateConfig(newConfig) {
|
|
|
Object.assign(config, newConfig);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
* 增强版请求封装(优先使用传入IP,否则用页面域名)
|
|
|
* @param {Object} options 请求配置
|
|
|
* @param {string} options.url 请求路径
|
|
|
* @param {string} [options.ip] 显式指定的服务端IP
|
|
|
* @param {'GET'|'POST'|'PUT'|'DELETE'} [options.method='GET'] 请求方法
|
|
|
* @param {Object} [options.data] 请求数据
|
|
|
* @returns {Promise} 返回请求结果
|
|
|
*/
|
|
|
export default async function request(options) {
|
|
|
const {
|
|
|
url,
|
|
|
ip,
|
|
|
method = 'GET',
|
|
|
data,
|
|
|
...rest
|
|
|
} = options;
|
|
|
|
|
|
// 优先使用传入IP,否则用页面域名
|
|
|
|
|
|
// 获取登录句柄(请替换YOUR_HANDLE_KEY为实际使用的key)
|
|
|
const handle = uni.getStorageSync('HANDLE_KEY');
|
|
|
|
|
|
console.log('handle', handle);
|
|
|
const ipAddres = uni.getStorageSync('IP_ADDRESS');
|
|
|
console.log('ipAddres', ipAddres);
|
|
|
const targetIp = ip || ipAddres || (typeof window !== 'undefined' ? window.location.hostname : '127.0.0.1');
|
|
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
const fullUrl = `http://${targetIp}:${config.port}${url}`;
|
|
|
console.log('请求URL:', fullUrl);
|
|
|
const res = await uni.request({
|
|
|
url: fullUrl,
|
|
|
method,
|
|
|
data,
|
|
|
header: {
|
|
|
...(handle ? {
|
|
|
'Authorization': `Bearer ${handle}`
|
|
|
} : {}),
|
|
|
...(rest.header || {})
|
|
|
},
|
|
|
...rest
|
|
|
});
|
|
|
if (res.data.code === 401) {
|
|
|
console.log(res.data.msg);
|
|
|
// 改用 redirectTo 或 reLaunch
|
|
|
uni.reLaunch({
|
|
|
url: '/pages/login/login'
|
|
|
});
|
|
|
}
|
|
|
|
|
|
return res; // 返回响应数据
|
|
|
} catch (err) {
|
|
|
console.error('请求失败:', err);
|
|
|
throw err;
|
|
|
}
|
|
|
} |