import { getToken, clearAuthData } from './auth'; // API基础URL const API_BASE_URL = 'https://77.smartvideo.py.qikongjian.com'; /** * 统一的API请求方法 */ export const apiRequest = async ( endpoint: string, options: RequestInit = {} ): Promise => { const token = getToken(); // 构建请求头 const headers: Record = { 'Accept': 'application/json', 'Content-Type': 'application/json', ...(options.headers as Record), }; // 添加token到请求头(如果存在) if (token) { headers['X-EASE-ADMIN-TOKEN'] = token; } try { const response = await fetch(`${API_BASE_URL}${endpoint}`, { ...options, headers, }); // 检查响应状态 if (!response.ok) { if (response.status === 401) { // Token过期或无效 clearAuthData(); window.location.href = '/login'; throw new Error('身份验证失败,请重新登录'); } throw new Error(`请求失败: ${response.status}`); } const data = await response.json(); // 检查业务状态码 if (data.code === '401' || data.status === 401) { clearAuthData(); window.location.href = '/login'; throw new Error('身份验证失败,请重新登录'); } return data; } catch (error) { console.error('API request failed:', error); throw error; } }; /** * GET请求 */ export const apiGet = (endpoint: string, options: RequestInit = {}) => { return apiRequest(endpoint, { ...options, method: 'GET', }); }; /** * POST请求 */ export const apiPost = (endpoint: string, data?: any, options: RequestInit = {}) => { return apiRequest(endpoint, { ...options, method: 'POST', body: data ? JSON.stringify(data) : undefined, }); }; /** * PUT请求 */ export const apiPut = (endpoint: string, data?: any, options: RequestInit = {}) => { return apiRequest(endpoint, { ...options, method: 'PUT', body: data ? JSON.stringify(data) : undefined, }); }; /** * DELETE请求 */ export const apiDelete = (endpoint: string, options: RequestInit = {}) => { return apiRequest(endpoint, { ...options, method: 'DELETE', }); }; /** * 文件上传请求 */ export const apiUpload = async (endpoint: string, formData: FormData, options: RequestInit = {}) => { const token = getToken(); // 构建请求头(文件上传时不设置Content-Type,让浏览器自动设置) const headers: Record = { 'Accept': 'application/json', ...(options.headers as Record), }; // 添加token到请求头(如果存在) if (token) { headers['X-EASE-ADMIN-TOKEN'] = token; } try { const response = await fetch(`${API_BASE_URL}${endpoint}`, { ...options, method: 'POST', headers, body: formData, }); // 检查响应状态 if (!response.ok) { if (response.status === 401) { // Token过期或无效 clearAuthData(); window.location.href = '/login'; throw new Error('身份验证失败,请重新登录'); } throw new Error(`请求失败: ${response.status}`); } const data = await response.json(); // 检查业务状态码 if (data.code === '401' || data.status === 401) { clearAuthData(); window.location.href = '/login'; throw new Error('身份验证失败,请重新登录'); } return data; } catch (error) { console.error('API request failed:', error); throw error; } };