28 lines
1007 B
JavaScript
28 lines
1007 B
JavaScript
// 统一 JSON fetch 封装:注入 Bearer token,解析 JSON/文本,非 2xx 抛带 status 的 Error。
|
|
// (login / create_user / SSE / 文件下载 因 header / 流式 / blob 特殊,仍各自手写 fetch)
|
|
import { state } from "./state.js";
|
|
|
|
export async function api(method, path, body) {
|
|
const opts = { method, headers: {} };
|
|
if (state.token) opts.headers["Authorization"] = "Bearer " + state.token;
|
|
if (body !== undefined) {
|
|
opts.headers["Content-Type"] = "application/json";
|
|
opts.body = JSON.stringify(body);
|
|
}
|
|
const r = await fetch(path, opts);
|
|
let data = null;
|
|
const ct = r.headers.get("content-type") || "";
|
|
if (ct.includes("application/json")) {
|
|
try { data = await r.json(); } catch (e) {}
|
|
} else {
|
|
data = await r.text();
|
|
}
|
|
if (!r.ok) {
|
|
const msg = (data && data.detail) || data || (r.status + " " + r.statusText);
|
|
const err = new Error(typeof msg === "string" ? msg : JSON.stringify(msg));
|
|
err.status = r.status;
|
|
throw err;
|
|
}
|
|
return data;
|
|
}
|