// utils/request.ts interface RequestOptions extends RequestInit { params?: Record; timeout?: number; } class Request { private baseUrl: string; private timeout: number; constructor(baseUrl: string = '', timeout: number = 10000) { this.baseUrl = baseUrl; this.timeout = timeout; } private getUrl(url: string): string { if (url.startsWith('http')) return url; return this.baseUrl + url; } private async handleResponse(response: Response) { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } return response.json(); } private async withTimeout(promise: Promise, timeout: number): Promise { return Promise.race([ promise, new Promise((_, reject) => setTimeout(() => reject(new Error('Request timeout')), timeout) ) ]); } async request(url: string, options: RequestOptions = {}): Promise { const { method = 'GET', headers = {}, body, params, timeout = this.timeout, ...restOptions } = options; let fullUrl = this.getUrl(url); // 处理查询参数 if (params) { const searchParams = new URLSearchParams(params); fullUrl += (fullUrl.includes('?') ? '&' : '?') + searchParams.toString(); } const config: RequestInit = { method, headers: { 'Content-Type': 'application/json', ...headers }, ...restOptions }; if (body) { config.body = typeof body === 'string' ? body : JSON.stringify(body); } try { const response = await this.withTimeout(fetch(fullUrl, config), timeout); return await this.handleResponse(response); } catch (error) { throw error; } } get(url: string, options?: Omit) { return this.request(url, { ...options, method: 'GET' }); } post(url: string, data?: any, options?: Omit) { return this.request(url, { ...options, method: 'POST', body: data }); } put(url: string, data?: any, options?: Omit) { return this.request(url, { ...options, method: 'PUT', body: data }); } delete(url: string, options?: Omit) { return this.request(url, { ...options, method: 'DELETE' }); } } // 创建默认实例 const request = new Request('https://usersource.landwu.com/api'); export default request;