/** * HTTP 请求工具类 * 封装 XMLHttpRequest,支持 GET/POST 请求 */ export class HttpUtil { /** * 发送 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'; 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'); 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)); }); } }