import { useUserStore } from '@/store'; const BASE_URL = '/api/v1'; // 后端统一响应格式 export interface ApiResponse { code: number; message: string; data: T; } // 列表响应格式 export interface ListResponse { list: T[]; total: number; } // 通用请求函数 async function request( method: string, url: string, body?: any, params?: Record ): Promise { // 构建 URL(含 query params) let fullUrl = `${BASE_URL}${url}`; if (params) { const searchParams = new URLSearchParams(); Object.entries(params).forEach(([key, value]) => { if (value !== undefined && value !== null && value !== '') { searchParams.append(key, String(value)); } }); const qs = searchParams.toString(); if (qs) fullUrl += `?${qs}`; } // 获取 token const token = useUserStore.getState().token; const headers: Record = { 'Content-Type': 'application/json', }; if (token) { headers['Authorization'] = `Bearer ${token}`; } const response = await fetch(fullUrl, { method, headers, body: body ? JSON.stringify(body) : undefined, }); if (response.status === 401) { useUserStore.getState().logout(); window.location.href = '/login'; throw new Error('登录已过期,请重新登录'); } const json: ApiResponse = await response.json(); if (json.code && json.code !== 200) { throw new Error(json.message || '请求失败'); } return json.data; } // 导出便捷方法 export const http = { get: (url: string, params?: Record) => request('GET', url, undefined, params), post: (url: string, body?: any) => request('POST', url, body), put: (url: string, body?: any) => request('PUT', url, body), delete: (url: string) => request('DELETE', url), }; export default http;