const TOKEN_KEY = 'nomadro_admin_token' /** 生产环境走同域 /api 或通过 VITE_API_BASE 指定 */ export const API_BASE = import.meta.env.VITE_API_BASE || '' export function getToken() { return localStorage.getItem(TOKEN_KEY) || '' } export function setToken(t: string) { localStorage.setItem(TOKEN_KEY, t) } export function clearToken() { localStorage.removeItem(TOKEN_KEY) } export async function api(path: string, init: RequestInit = {}): Promise { const headers: Record = { 'Content-Type': 'application/json', ...(init.headers as Record | undefined), } const token = getToken() if (token) headers.Authorization = `Bearer ${token}` const res = await fetch(`${API_BASE}${path}`, { ...init, headers }) if (res.status === 401) { clearToken() if (!path.includes('/login')) window.location.href = '/login' } const data = await res.json().catch(() => ({})) if (!res.ok) { const err = data as { detail?: string; message?: string } throw new Error(err.detail || err.message || '请求失败') } return data as T }