export type HttpMethod = 'GET' | 'POST' | 'DELETE'; export const CONFIG = { CLIENT_BASE: 'http://localhost:8081', RUOYI_BASE: 'http://8.138.23.49:8085', //RUOYI_BASE: 'http://192.168.1.89:8085', SSE_URL: 'http://8.138.23.49:8085/monitor/account/events' } as const; function resolveBase(path: string): string { if (path.startsWith('/monitor/') || path.startsWith('/system/') || path.startsWith('/tool/banma')) { return CONFIG.RUOYI_BASE; } return CONFIG.CLIENT_BASE; } function buildQuery(params?: Record): string { if (!params) return ''; const query = new URLSearchParams(); Object.entries(params).forEach(([key, value]) => { if (value != null) query.append(key, String(value)); }); return query.toString() ? `?${query}` : ''; } async function getToken(): Promise { try { const tokenModule = await import('../utils/token'); return tokenModule.getToken() || ''; } catch { return ''; } } async function request(path: string, options: RequestInit & { signal?: AbortSignal }): Promise { const token = await getToken(); const res = await fetch(`${resolveBase(path)}${path}`, { credentials: 'omit', cache: 'no-store', ...options, headers: { 'Content-Type': 'application/json', ...(token ? { 'Authorization': `Bearer ${token}` } : {}), ...options.headers } }); if (!res.ok) { const text = await res.text().catch(() => ''); throw new Error(text || `HTTP ${res.status}`); } const contentType = res.headers.get('content-type') || ''; if (contentType.includes('application/json')) { const json: any = await res.json(); if (json.code !== undefined && json.code !== 0 && json.code !== 200) { throw new Error(json.msg || '请求失败'); } return json as T; } return (await res.text()) as unknown as T; } export const http = { get(path: string, params?: Record, signal?: AbortSignal) { return request(`${path}${buildQuery(params)}`, { method: 'GET', signal }); }, post(path: string, body?: unknown, signal?: AbortSignal) { return request(path, { method: 'POST', body: body ? JSON.stringify(body) : undefined, signal }); }, delete(path: string) { return request(path, { method: 'DELETE' }); }, async upload(path: string, form: FormData, signal?: AbortSignal) { const token = await getToken(); const res = await fetch(`${resolveBase(path)}${path}`, { method: 'POST', body: form, credentials: 'omit', cache: 'no-store', headers: token ? { 'Authorization': `Bearer ${token}` } : {}, signal }); if (!res.ok) { const text = await res.text().catch(() => ''); throw new Error(text || `HTTP ${res.status}`); } const contentType = res.headers.get('content-type') || ''; if (contentType.includes('application/json')) { const json: any = await res.json(); if (json.code !== undefined && json.code !== 0 && json.code !== 200) { throw new Error(json.msg || '请求失败'); } return json as T; } return (await res.text()) as unknown as T; } };