client.ts 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import axios from "axios";
  2. import { Toast } from "@douyinfe/semi-ui";
  3. // Determine base URL from environment variables, or fallback to default
  4. const DEFAULT_BASE_URL = "http://43.106.118.91:8000";
  5. const getBaseUrl = () => {
  6. const winConfig =
  7. typeof window !== "undefined"
  8. ? (window as unknown as { CONFIG?: { API_BASE_URL?: string } }).CONFIG?.API_BASE_URL
  9. : undefined;
  10. if (typeof winConfig === "string" && winConfig) return winConfig;
  11. if (typeof import.meta !== "undefined" && import.meta.env && import.meta.env.VITE_API_BASE_URL) {
  12. return import.meta.env.VITE_API_BASE_URL;
  13. }
  14. return DEFAULT_BASE_URL;
  15. };
  16. export const client = axios.create({
  17. baseURL: getBaseUrl(),
  18. });
  19. client.interceptors.response.use(
  20. (response) => response,
  21. (error) => {
  22. // Check if error has a response (server responded with status code outside 2xx)
  23. if (error.response) {
  24. const { status, data } = error.response;
  25. const message = data?.detail || data?.message || "请求失败";
  26. // Handle specific status codes
  27. if (status >= 500) {
  28. Toast.error(`服务器错误 (${status}): ${message}`);
  29. } else if (status >= 400) {
  30. Toast.error(`请求错误 (${status}): ${message}`);
  31. }
  32. } else if (error.request) {
  33. // The request was made but no response was received
  34. Toast.error("网络错误: 无法连接到服务器");
  35. } else {
  36. // Something happened in setting up the request that triggered an Error
  37. Toast.error(`请求配置错误: ${error.message}`);
  38. }
  39. return Promise.reject(error);
  40. },
  41. );
  42. export async function request<T>(
  43. path: string,
  44. init?: { method?: string; data?: unknown; params?: Record<string, unknown> },
  45. ): Promise<T> {
  46. const method = init?.method || "GET";
  47. const response = await client.request<T>({
  48. url: path,
  49. method,
  50. params: init?.params,
  51. data: init?.data,
  52. });
  53. return response.data;
  54. }