/** 配送点后台 HTTP 客户端,使用独立 API 前缀和 JWT 存储键。 */ import { getToken } from '@/utils/auth'; const apiBaseURL = import.meta.env.VITE_API_BASE_URL || 'http://localhost:12426/heqi/delivery/v1'; export type PageResult = { total: number; list: T[] }; /** * 发送配送点后台请求。 * 参数:path 为 API 相对路径,init 为标准 Fetch 请求选项。 * 返回值:统一响应中的 details;网络、协议或业务失败时抛出可读错误。 */ export async function request(path: string, init?: RequestInit): Promise { const token = getToken(); let response: Response; try { response = await fetch(`${apiBaseURL}${path}`, { ...init, headers: { 'Content-Type': 'application/json', ...(token ? { Authorization: token } : {}), ...(init?.headers ?? {}), }, }); } catch { throw new Error('无法连接服务器,请确认服务已启动'); } const responseText = await response.text(); let payload: { code?: number; message?: string; details?: T }; try { payload = responseText ? JSON.parse(responseText) : {}; } catch { // 网关、代理和不存在的路由可能返回纯文本,不能把底层 JSON 异常暴露给用户。 if (!response.ok) throw new Error(`请求失败(HTTP ${response.status})`); throw new Error('服务器返回了无法识别的数据格式'); } if (!response.ok || payload.code !== 0) throw new Error(payload.message || '请求失败'); return payload.details as T; }