// 后台 API 调用封装:自动携带 JWT,401 清理并抛出“未登录” const TOKEN_KEY = 'pasl_token' export function getToken(): string | null { 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, opts: RequestInit = {}): Promise { const headers: Record = { ...(opts.headers as Record || {}) } if (opts.body && typeof opts.body === 'string' && !headers['Content-Type']) { headers['Content-Type'] = 'application/json' } const tok = getToken() if (tok) headers['Authorization'] = `Bearer ${tok}` const res = await fetch(path, { ...opts, headers }) if (res.status === 401) { clearToken() throw new Error('未登录或登录已过期') } if (!res.ok) { let msg = `HTTP ${res.status}` try { const j = await res.json() msg = j.detail || JSON.stringify(j) } catch { /* ignore */ } throw new Error(msg) } if (res.status === 204) return undefined as any return res.json() }