let csrfToken = '' export function setCsrf(value) { csrfToken = value || '' } export async function api(path, options = {}) { const method = options.method || 'GET' const response = await fetch(`/api/admin${path}`, { credentials: 'same-origin', ...options, headers: { ...(options.body ? { 'Content-Type': 'application/json' } : {}), ...(!['GET', 'HEAD'].includes(method) && csrfToken ? { 'X-CSRF-Token': csrfToken } : {}), ...options.headers, }, }) if (!response.ok) { let message = `请求失败(${response.status})` try { message = (await response.json()).message || message } catch { /* empty response */ } const error = new Error(message) error.status = response.status throw error } return response.status === 204 ? null : response.json() }