初始化项目
This commit is contained in:
38
apps/web/src/lib/api.js
Normal file
38
apps/web/src/lib/api.js
Normal file
@@ -0,0 +1,38 @@
|
||||
const BASE_URL = import.meta.env.VITE_SERVER_BASE_URL || "http://localhost:3001";
|
||||
|
||||
export function getToken() {
|
||||
return localStorage.getItem("bb_token") || "";
|
||||
}
|
||||
|
||||
export function setToken(token) {
|
||||
if (token) localStorage.setItem("bb_token", token);
|
||||
else localStorage.removeItem("bb_token");
|
||||
}
|
||||
|
||||
export async function apiFetch(path, options = {}) {
|
||||
const headers = new Headers(options.headers || {});
|
||||
headers.set("Accept", "application/json");
|
||||
|
||||
if (!(options.body instanceof FormData) && options.body != null) {
|
||||
headers.set("Content-Type", "application/json");
|
||||
}
|
||||
|
||||
const token = getToken();
|
||||
if (token) headers.set("Authorization", `Bearer ${token}`);
|
||||
|
||||
const res = await fetch(`${BASE_URL}${path}`, { ...options, headers });
|
||||
|
||||
const contentType = res.headers.get("content-type") || "";
|
||||
const isJson = contentType.includes("application/json");
|
||||
const payload = isJson ? await res.json().catch(() => null) : await res.text().catch(() => "");
|
||||
|
||||
if (!res.ok) {
|
||||
const message = payload?.message || `HTTP ${res.status}`;
|
||||
const err = new Error(message);
|
||||
err.status = res.status;
|
||||
err.payload = payload;
|
||||
throw err;
|
||||
}
|
||||
|
||||
return payload;
|
||||
}
|
||||
Reference in New Issue
Block a user