import { API_BASE_URL } from '../utils/constants'; interface ApiResponse { data: T; status: number; } class ApiClient { private baseURL: string; constructor(baseURL: string) { this.baseURL = baseURL; } private getAuthHeaders(): Record { const token = localStorage.getItem('authToken') || localStorage.getItem('token'); // console.log('API 调用 token:', token ? token.substring(0, 10) + '...' : 'null'); return { 'Content-Type': 'application/json', ...(token && { Authorization: `Bearer ${token}` }), }; } // 新式的 API 调用方法,返回 { data, status } async get(url: string): Promise> { const response = await fetch(`${this.baseURL}${url}`, { method: 'GET', headers: this.getAuthHeaders(), }); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.message || 'Request failed'); } const data = await response.json(); return { data, status: response.status }; } async post(url: string, body?: any): Promise> { const response = await fetch(`${this.baseURL}${url}`, { method: 'POST', headers: this.getAuthHeaders(), body: body ? JSON.stringify(body) : undefined, }); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.message || 'Request failed'); } const data = await response.json(); return { data, status: response.status }; } async put(url: string, body?: any): Promise> { const response = await fetch(`${this.baseURL}${url}`, { method: 'PUT', headers: this.getAuthHeaders(), body: body ? JSON.stringify(body) : undefined, }); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.message || 'Request failed'); } const data = await response.json(); return { data, status: response.status }; } async delete(url: string): Promise> { const response = await fetch(`${this.baseURL}${url}`, { method: 'DELETE', headers: this.getAuthHeaders(), }); if (!response.ok) { const errorData = await response.json(); throw new Error(errorData.message || 'Request failed'); } const data = await response.json(); return { data, status: response.status }; } // 保持原有的 API 兼容性方法,接受路径和选项参数并返回原始 Response async request(path: string, options: RequestInit = {}): Promise { const token = localStorage.getItem('authToken'); const headers = new Headers(options.headers); if (token) { headers.set('Authorization', `Bearer ${token}`); } // 构建完整 URL let url = path; if (!path.startsWith('http')) { const cleanPath = path.startsWith('/') ? path : `/${path}`; url = `${this.baseURL}${cleanPath}`; } const response = await fetch(url, { ...options, headers, }); if (response.status === 401) { localStorage.removeItem('authToken'); window.location.reload(); throw new Error('Unauthorized'); } return response; } } export const apiClient = new ApiClient(API_BASE_URL);