24 lines
913 B
JavaScript
24 lines
913 B
JavaScript
const TOKEN_KEY = 'token';
|
|
|
|
export function getToken() {
|
|
return localStorage.getItem(TOKEN_KEY);
|
|
}
|
|
|
|
export function setToken(t) {
|
|
t ? localStorage.setItem(TOKEN_KEY, t) : localStorage.removeItem(TOKEN_KEY);
|
|
}
|
|
|
|
/** 登录态变更通知:登录/退出/头像更新后触发,Layout 监听后重新拉取当前用户 */
|
|
export function notifyAuthChange() {
|
|
window.dispatchEvent(new Event('authchange'));
|
|
}
|
|
|
|
export async function request(path, { method = 'GET', body, auth = true } = {}) {
|
|
const headers = { 'Content-Type': 'application/json' };
|
|
if (auth && getToken()) headers.Authorization = 'Bearer ' + getToken();
|
|
const res = await fetch('/api' + path, { method, headers, body: body ? JSON.stringify(body) : undefined });
|
|
const data = await res.json().catch(() => ({}));
|
|
if (!res.ok) { const err = new Error(data.error || '请求失败'); err.status = res.status; throw err; }
|
|
return data;
|
|
}
|