/** 全局认证 fetch 客户端 */ let tokenGetter: () => string | null = () => null; export function setTokenGetter(fn: () => string | null) { tokenGetter = fn; } export async function fetchJson(url: string, options?: RequestInit): Promise { const token = tokenGetter(); const res = await fetch(url, { ...options, headers: { ...options?.headers, ...(token ? { Authorization: `Bearer ${token}` } : {}), }, }); if (res.status === 401) { window.dispatchEvent(new CustomEvent('auth:unauthorized')); throw new Error('Unauthorized'); } if (!res.ok) throw new Error(`API error: ${res.status} ${res.statusText}`); return res.json(); }