diff --git a/web/src/api.js b/web/src/api.js index 16ea023..e4139a9 100644 --- a/web/src/api.js +++ b/web/src/api.js @@ -1,10 +1,27 @@ -const BASE = "" +import { clearStoredAuth, getAccessToken, getStoredAuth, saveStoredAuth } from "./auth"; + +const BASE = "" async function request(path, opts = {}) { + const token = getAccessToken(); + const headers = { "Content-Type": "application/json", ...opts.headers }; + if (token) headers.Authorization = `Bearer ${token}`; + const res = await fetch(`${BASE}${path}`, { - headers: { "Content-Type": "application/json", ...opts.headers }, + headers, ...opts, }); + + const renewedToken = res.headers.get("x-license-token"); + if (renewedToken) { + const current = getStoredAuth() || {}; + saveStoredAuth({ ...current, token: renewedToken }); + } + + if (res.status === 401) { + clearStoredAuth(); + } + if (!res.ok) { const err = await res.json().catch(() => ({ error: res.statusText })); throw new Error(err.error || "请求失败");