/** * 请求封装 * 根据环境自动切换 API 地址 */ import { getCurrentConfig, CURRENT_ENV } from '@/config/index.js' // 缓存配置 let configCache = null // 初始化配置 const initConfig = async () => { if (!configCache) { configCache = await getCurrentConfig() console.log('当前环境:', configCache.env, '| API 地址:', configCache.baseUrl) } return configCache } // 预加载配置 initConfig() /** * 统一请求方法 */ export const request = async (options) => { // 确保配置已加载 const config = await initConfig() const { baseUrl, timeout, debug } = config return new Promise((resolve, reject) => { // 获取 token const token = uni.getStorageSync('token') || '' if (debug) { console.log('Request:', options.method || 'GET', options.url, options.data) } uni.request({ url: baseUrl + options.url, method: options.method || 'GET', data: options.data || {}, header: { 'Content-Type': 'application/json', 'Authorization': token ? `Bearer ${token}` : '' }, timeout: timeout, success: (res) => { const { statusCode, data } = res if (debug) { console.log('Response:', statusCode, data) } // HTTP 状态码判断 if (statusCode === 200) { // 业务状态码判断 if (data.code === 0 || data.code === 200 || data.success) { resolve(data) } else { // 业务错误 uni.showToast({ title: data.message || data.msg || '请求失败', icon: 'none', duration: 2000 }) reject(data) } } else if (statusCode === 401) { // 未授权,清除缓存并跳转登录页 uni.removeStorageSync('userInfo') uni.removeStorageSync('token') uni.reLaunch({ url: '/pages/login/login' }) reject({ message: '未授权,请重新登录' }) } else { // 其他错误 uni.showToast({ title: '网络请求失败', icon: 'none', duration: 2000 }) reject(res) } }, fail: (err) => { console.error('Request fail:', err) uni.showToast({ title: '网络连接失败', icon: 'none', duration: 2000 }) reject(err) } }) }) } /** * 快捷请求方法 */ export const get = (url, data) => { return request({ url, method: 'GET', data }) } export const post = (url, data) => { return request({ url, method: 'POST', data }) } export const put = (url, data) => { return request({ url, method: 'PUT', data }) } export const del = (url, data) => { return request({ url, method: 'DELETE', data }) } export default request