import axios from "axios"; import { Toast } from "@douyinfe/semi-ui"; // Determine base URL from environment variables, or fallback to default const DEFAULT_BASE_URL = "http://localhost:8000"; // Handle various environment variable formats (Vite uses import.meta.env.VITE_*) const getBaseUrl = () => { if (typeof import.meta !== "undefined" && import.meta.env && import.meta.env.VITE_API_BASE_URL) { return import.meta.env.VITE_API_BASE_URL; } return DEFAULT_BASE_URL; }; export const client = axios.create({ baseURL: getBaseUrl(), }); client.interceptors.response.use( (response) => response, (error) => { // Check if error has a response (server responded with status code outside 2xx) if (error.response) { const { status, data } = error.response; const message = data?.detail || data?.message || "请求失败"; // Handle specific status codes if (status >= 500) { Toast.error(`服务器错误 (${status}): ${message}`); } else if (status >= 400) { Toast.error(`请求错误 (${status}): ${message}`); } } else if (error.request) { // The request was made but no response was received Toast.error("网络错误: 无法连接到服务器"); } else { // Something happened in setting up the request that triggered an Error Toast.error(`请求配置错误: ${error.message}`); } return Promise.reject(error); }, ); export async function request( path: string, init?: { method?: string; data?: unknown; params?: Record }, ): Promise { const method = init?.method || "GET"; const response = await client.request({ url: path, method, params: init?.params, data: init?.data, }); return response.data; }