/** * HTTP 请求工具类 * 封装 XMLHttpRequest,支持 GET/POST 请求,支持 JWT 认证 */ export class HttpUtil { /** 认证 token */ private static _authToken: string | null = null; /** * 设置认证 token * @param token JWT token */ static setAuthToken(token: string | null): void { HttpUtil._authToken = token; console.log(`[HttpUtil] Auth token ${token ? '已设置' : '已清除'}`); } /** * 获取认证 token */ static getAuthToken(): string | null { return HttpUtil._authToken; } /** * 发送 GET 请求 * @param url 请求 URL * @param timeout 超时时间(毫秒),默认 10000 * @returns Promise */ static get(url: string, timeout: number = 10000): Promise { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('GET', url, true); xhr.timeout = timeout; xhr.responseType = 'json'; // 设置认证头 if (HttpUtil._authToken) { xhr.setRequestHeader('Authorization', `Bearer ${HttpUtil._authToken}`); } xhr.onload = () => { if (xhr.status >= 200 && xhr.status < 300) { resolve(xhr.response as T); } else { reject(new Error(`HTTP 错误: ${xhr.status}`)); } }; xhr.onerror = () => { reject(new Error('网络请求失败')); }; xhr.ontimeout = () => { reject(new Error('请求超时')); }; xhr.send(); }); } /** * 发送 POST 请求 * @param url 请求 URL * @param data 请求体数据 * @param timeout 超时时间(毫秒),默认 10000 * @returns Promise */ static post(url: string, data: object, timeout: number = 10000): Promise { return new Promise((resolve, reject) => { const xhr = new XMLHttpRequest(); xhr.open('POST', url, true); xhr.timeout = timeout; xhr.responseType = 'json'; xhr.setRequestHeader('Content-Type', 'application/json'); // 设置认证头 if (HttpUtil._authToken) { xhr.setRequestHeader('Authorization', `Bearer ${HttpUtil._authToken}`); } xhr.onload = () => { if (xhr.status >= 200 && xhr.status < 300) { resolve(xhr.response as T); } else { reject(new Error(`HTTP 错误: ${xhr.status}`)); } }; xhr.onerror = () => { reject(new Error('网络请求失败')); }; xhr.ontimeout = () => { reject(new Error('请求超时')); }; xhr.send(JSON.stringify(data)); }); } }