p01 / frontend /src /api.ts
lbb123's picture
Upload 45 files
779ffa9 verified
Raw History Blame Contribute Delete
1.18 kB
// 后台 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<T = any>(path: string, opts: RequestInit = {}): Promise<T> {
const headers: Record<string, string> = { ...(opts.headers as Record<string, string> || {}) }
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()
}