/** * 后端 API 客户端。 * * 默认走同源代理:页面请求相对路径 /api/*,由 next.config.ts 的 rewrites 转发到后端 * (默认 http://127.0.0.1:8000,可用环境变量 BACKEND_API_URL 覆盖)。 * 需要直连(不走代理)时可用 NEXT_PUBLIC_API_BASE 显式指定后端地址(含 /api)。 */ const explicitBase = process.env.NEXT_PUBLIC_API_BASE?.replace(/\/$/, ""); const BASE = explicitBase ?? "/api"; export async function apiGet(path: string): Promise { const resp = await fetch(`${BASE}${path}`); if (!resp.ok) throw new Error(`GET ${path} → ${resp.status}: ${await resp.text()}`); return (await resp.json()) as T; } export async function apiPost(path: string, body: unknown): Promise { const resp = await fetch(`${BASE}${path}`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(body), }); if (!resp.ok) { const text = await resp.text(); throw new Error(`POST ${path} → ${resp.status}: ${text.slice(0, 300)}`); } return (await resp.json()) as T; } export interface ApiError { status: number; message: string; }