File size: 1,414 Bytes
e4b7d6f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
/**
 * 全局 API 环境配置
 * 自动识别开发环境、生产环境、Tauri 桌面端、Capacitor 移动端
 */
export const getBaseUrl = () => {
  // 1. 优先使用环境变量中配置的地址
  const envBaseUrl = import.meta.env.VITE_API_BASE_URL;
  if (envBaseUrl) return envBaseUrl;

  // 2. 如果是打包环境 (Tauri 或 Capacitor),必须使用线上公网地址
  if (
    typeof window !== 'undefined' && 
    (window.location.protocol === 'tauri:' || 
     window.location.protocol === 'capacitor:' || 
     window.location.hostname === 'localhost' === false)
  ) {
    return 'https://duqing2026-codex-ai-platform.hf.space';
  }

  // 3. 本地开发环境且是浏览器访问,返回空字符串(走 Vite Proxy 代理)
  return '';
};

/**
 * 全局 Fetch 拦截器安装函数
 */
export const setupGlobalFetch = () => {
  const { fetch: originalFetch } = window;
  const baseUrl = getBaseUrl();

  if (!baseUrl) return; // 如果没有基准地址(本地开发),不进行拦截

  window.fetch = async (...args) => {
    let [resource, config] = args;

    // 如果是字符串路径且以 /api 开头,则补齐基准地址
    if (typeof resource === 'string' && resource.startsWith('/api')) {
      resource = `${baseUrl}${resource}`;
    }

    return originalFetch(resource, config);
  };

  console.log(`[API] 全局拦截器已启动,基准地址: ${baseUrl}`);
};