Files
vf_react/src/utils/apiConfig.js
2025-10-20 21:25:33 +08:00

57 lines
1.5 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/**
* API 配置工具
* 提供统一的 API 基础地址获取方法
*/
/**
* 获取 API 基础 URL
*
* 工作原理:
* - 生产环境: 返回空字符串,使用相对路径
* - Mock 模式 (REACT_APP_API_URL=""): 返回空字符串,让 MSW 拦截请求
* - 开发模式: 返回后端服务器地址
*
* @returns {string} API 基础地址
*
* @example
* const response = await fetch(getApiBase() + '/api/users');
*/
export const getApiBase = () => {
// 生产环境使用相对路径
if (process.env.NODE_ENV === 'production') {
return '';
}
// 检查是否定义了 REACT_APP_API_URL包括空字符串
// 使用 !== undefined 而不是 || 运算符,正确处理空字符串
const apiUrl = process.env.REACT_APP_API_URL;
if (apiUrl !== undefined) {
return apiUrl; // Mock 模式下返回 '',其他情况返回配置的值
}
// 未配置时的默认后端地址
return 'http://49.232.185.254:5001';
};
/**
* 检查是否处于 Mock 模式
* @returns {boolean}
*/
export const isMockMode = () => {
return process.env.REACT_APP_ENABLE_MOCK === 'true';
};
/**
* 获取完整的 API URL
* @param {string} path - API 路径,应以 / 开头
* @returns {string} 完整的 URL
*
* @example
* const url = getApiUrl('/api/users');
* // Mock 模式: '/api/users'
* // 开发模式: 'http://49.232.185.254:5001/api/users'
*/
export const getApiUrl = (path) => {
return getApiBase() + path;
};