3v324v23's picture
feat:让打包的 App 可以访问线上数据
e4b7d6f
/**
* 全局 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}`);
};