/** * API 配置模块 * 提供统一的 API 基础 URL 和常量定义 */ // API 基础配置 window.API_CONFIG = { // ✅ 修改为相对路径(通过同域名 nginx 转发到后端 8001 端口) baseURL: '', // 空字符串表示使用当前域名的根路径 // API 版本前缀 version: '/api', // 超时时间 (毫秒) timeout: 30000, // 认证相关 auth: { tokenKey: 'smart_center_token', refreshTokenKey: 'smart_center_refresh_token' }, // 请求头配置 headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' }, // API 端点 endpoints: { // 认证相关 login: '/auth/login', register: '/auth/register', logout: '/auth/logout', userinfo: '/auth/userinfo', // 模块管理 modules: '/modules', moduleDetail: '/modules/detail', // AI 服务 aiChat: '/ai/chat', aiGenerate: '/ai/generate', // 文件管理 files: '/files', upload: '/files/upload', // 用户管理 users: '/users', userProfile: '/users/profile' } }; // 工具函数:获取完整 API URL window.getApiUrl = function(endpoint) { return `${window.API_CONFIG.baseURL}${window.API_CONFIG.version}${endpoint}`; }; // 工具函数:获取认证 Token window.getToken = function() { return localStorage.getItem(window.API_CONFIG.auth.tokenKey); }; // 工具函数:设置认证 Token window.setToken = function(token, expiresIn = 7200) { localStorage.setItem(window.API_CONFIG.auth.tokenKey, token); }; // 工具函数:清除 Token window.clearToken = function() { localStorage.removeItem(window.API_CONFIG.auth.tokenKey); localStorage.removeItem(window.API_CONFIG.auth.refreshTokenKey); }; // 工具函数:API 调用封装 window.apiRequest = async function(endpoint, options = {}) { const url = window.getApiUrl(endpoint); const defaultOptions = { headers: { ...window.API_CONFIG.headers }, timeout: window.API_CONFIG.timeout }; // 添加认证 token const token = window.getToken(); if (token) { defaultOptions.headers['Authorization'] = `Bearer ${token}`; } const finalOptions = { ...defaultOptions, ...options, headers: { ...defaultOptions.headers, ...(options.headers || {}) } }; try { const response = await fetch(url, finalOptions); if (!response.ok) { const errorData = await response.json().catch(() => ({})); throw new Error(errorData.detail || `HTTP ${response.status}`); } return await response.json(); } catch (error) { console.error('API 请求失败:', { url, error: error.message, endpoint }); throw error; } };