feat: 添加合规
This commit is contained in:
56
src/utils/apiConfig.js
Normal file
56
src/utils/apiConfig.js
Normal file
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
* 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;
|
||||
};
|
||||
Reference in New Issue
Block a user