window.API = (function() { 'use strict'; const BASE = '/api/v1'; let _agentKey = ''; async function request(method, path, body) { const headers = { 'Content-Type': 'application/json' }; const token = Auth.getToken(); if (token) headers['Authorization'] = 'Bearer ' + token; if (_agentKey) headers['X-Agent-Key'] = _agentKey; const opts = { method, headers }; if (body && method !== 'GET') opts.body = JSON.stringify(body); Logger.debug(`API ${method} ${path}`); let res; try { res = await fetch(BASE + path, opts); } catch (e) { Logger.error(`API fetch error: ${path} - ${e.message}`); throw new Error('网络请求失败,请检查网络连接'); } let data; try { data = await res.json(); } catch (e) { data = null; } if (!res.ok) { const msg = (data && data.detail) || `请求失败 (${res.status})`; Logger.error(`API error: ${path} - ${msg}`); const err = new Error(msg); err.status = res.status; err.data = data; throw err; } return data; } return { setAgentKey(k) { _agentKey = k; }, get: (path) => request('GET', path), post: (path, body) => request('POST', path, body), put: (path, body) => request('PUT', path, body), delete: (path) => request('DELETE', path), }; })();