Spaces:
Paused
Paused
Download frontend/src/api.ts from lbb123/p01: direct link, hf CLI and curl.
- Browser
- Download file 1.18 kB
-
https://huggingface.co/spaces/lbb123/p01/resolve/main/frontend/src/api.ts
- Command line
-
hf download hf://spaces/lbb123/p01/frontend/src/api.ts
-
curl -L -o api.ts https://huggingface.co/spaces/lbb123/p01/resolve/main/frontend/src/api.ts
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() | |
| } | |