| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061 |
- 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://43.106.118.91:8000";
- const getBaseUrl = () => {
- const winConfig =
- typeof window !== "undefined"
- ? (window as unknown as { CONFIG?: { API_BASE_URL?: string } }).CONFIG?.API_BASE_URL
- : undefined;
- if (typeof winConfig === "string" && winConfig) return winConfig;
- 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<T>(
- path: string,
- init?: { method?: string; data?: unknown; params?: Record<string, unknown> },
- ): Promise<T> {
- const method = init?.method || "GET";
- const response = await client.request<T>({
- url: path,
- method,
- params: init?.params,
- data: init?.data,
- });
- return response.data;
- }
|