You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

69 lines
1.6 KiB
JavaScript

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

// 全局配置
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;
}
}