// 统一请求封装 // 开发环境经 Vite 代理转发到后端(见 vite.config.js),生产可用 VITE_API_BASE 指定后端地址 const BASE = import.meta.env.VITE_API_BASE || '' function buildQuery(params) { const q = new URLSearchParams() Object.entries(params || {}).forEach(([k, v]) => { if (v !== undefined && v !== null && v !== '') q.append(k, v) }) const s = q.toString() return s ? '?' + s : '' } export async function request(path, { method = 'GET', body, params } = {}) { const url = BASE + path + buildQuery(params) const options = { method, headers: {} } if (body !== undefined) { options.headers['Content-Type'] = 'application/json' options.body = JSON.stringify(body) } let json try { const res = await fetch(url, options) json = await res.json() } catch (e) { throw new Error('网络异常,请稍后重试') } if (!json || json.code !== 0) { throw new Error((json && json.msg) || '请求失败') } return json.data }