创建评查点分组的API文件
This commit is contained in:
+37
-14
@@ -14,8 +14,9 @@ export type ApiResponse<T> = {
|
||||
export type QueryParams = Record<string, string | number | boolean | undefined>;
|
||||
|
||||
// 获取 API 基础 URL
|
||||
const API_BASE_URL = '172.18.0.100:3000';
|
||||
// const API_BASE_URL = '172.18.0.100:3000';
|
||||
// const API_BASE_URL = '172.16.0.119:9000/admin';
|
||||
const API_BASE_URL = 'http://nas.7bm.co:3000';
|
||||
|
||||
// 是否使用模拟数据(开发环境使用)
|
||||
const USE_MOCK_DATA = false; // 设置为true使用模拟数据,避免API连接问题
|
||||
@@ -24,22 +25,36 @@ const USE_MOCK_DATA = false; // 设置为true使用模拟数据,避免API连
|
||||
* 构建完整的 API URL
|
||||
*/
|
||||
function buildUrl(endpoint: string, params?: QueryParams): string {
|
||||
// 创建 URL 字符串
|
||||
const url = new URL(
|
||||
endpoint.startsWith('http') ? endpoint : `http://${API_BASE_URL}${endpoint.startsWith('/') ? endpoint : `/${endpoint}`}`,
|
||||
typeof window !== 'undefined' ? window.location.origin : 'http://localhost:3000'
|
||||
);
|
||||
let fullUrl;
|
||||
|
||||
// 添加查询参数
|
||||
if (params) {
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (value !== undefined) {
|
||||
url.searchParams.append(key, String(value));
|
||||
}
|
||||
});
|
||||
// 检查endpoint是否已经是完整URL
|
||||
if (endpoint.startsWith('http')) {
|
||||
fullUrl = endpoint;
|
||||
} else {
|
||||
// 确保API_BASE_URL格式正确
|
||||
const baseUrl = API_BASE_URL.endsWith('/') ? API_BASE_URL.slice(0, -1) : API_BASE_URL;
|
||||
const path = endpoint.startsWith('/') ? endpoint : `/${endpoint}`;
|
||||
fullUrl = `${baseUrl}${path}`;
|
||||
}
|
||||
|
||||
return url.toString();
|
||||
try {
|
||||
// 创建URL对象
|
||||
const url = new URL(fullUrl);
|
||||
|
||||
// 添加查询参数
|
||||
if (params) {
|
||||
Object.entries(params).forEach(([key, value]) => {
|
||||
if (value !== undefined) {
|
||||
url.searchParams.append(key, String(value));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return url.toString();
|
||||
} catch (error) {
|
||||
console.error('URL构建错误:', fullUrl, error);
|
||||
throw new Error(`无法构建URL: ${fullUrl}, 错误: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
// 超时控制
|
||||
@@ -48,6 +63,7 @@ const fetchWithTimeout = async (url: string, options: RequestInit, timeout = 500
|
||||
const id = setTimeout(() => controller.abort(), timeout);
|
||||
|
||||
try {
|
||||
console.log(`📦 API 端点: ${url}`);
|
||||
const response = await fetch(url, {
|
||||
...options,
|
||||
signal: controller.signal
|
||||
@@ -56,6 +72,13 @@ const fetchWithTimeout = async (url: string, options: RequestInit, timeout = 500
|
||||
return response;
|
||||
} catch (error) {
|
||||
clearTimeout(id);
|
||||
console.error(`📦 API请求失败: ${error}`);
|
||||
|
||||
// 检查是否是网络连接问题
|
||||
if (error instanceof TypeError && error.message.includes('fetch failed')) {
|
||||
console.error('网络连接错误,请检查API_BASE_URL配置是否正确');
|
||||
}
|
||||
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user