更新index.html,优化API调用函数,简化请求处理逻辑并增强错误处理

This commit is contained in:
Zhuym 2025-01-30 21:18:53 +08:00
parent f923ed0695
commit efc0c7cb50

View File

@ -493,12 +493,11 @@
localStorage.setItem('apiLogs', JSON.stringify(updatedLogs));
};
const handleApiCall = async (endpoint, method = 'GET', formData = null, config = {}) => {
const handleApiCall = async (endpoint, method = 'GET', formData = null, config) => {
try {
const options = {
method,
headers: {},
credentials: 'include', // 支持跨域请求携带 Cookie
headers: { 'Content-Type': 'application/json' }
};
let url = `${apiBase}${endpoint}`;
@ -507,37 +506,19 @@
if (method === 'GET' && config.queryParams) {
const params = new URLSearchParams();
config.queryParams.forEach(param => {
if (formData && formData[param]) {
params.append(param, formData[param]);
}
if (formData[param]) params.append(param, formData[param]);
});
url += `?${params.toString()}`;
}
// 处理请求体
if (['POST', 'PUT', 'PATCH'].includes(method)) {
if (formData instanceof FormData) {
// 文件上传时,不设置 Content-Type浏览器会自动处理
options.body = formData;
} else if (config.requestFormat === 'json') {
options.headers['Content-Type'] = 'application/json';
// 处理POST请求体
if (method === 'POST') {
if (config.requestFormat === 'json') {
options.body = JSON.stringify(formData);
} else {
options.headers['Content-Type'] = 'application/x-www-form-urlencoded';
options.body = new URLSearchParams(formData).toString();
}
}
// 发送请求
const res = await fetch(url, options);
// 检查 HTTP 状态码
if (!res.ok) {
const errorData = await res.json();
throw new Error(errorData.message || `HTTP error! Status: ${res.status}`);
}
// 解析响应数据
const data = await res.json();
setResponse(JSON.stringify(data, null, 2));
@ -560,13 +541,11 @@
});
}
// 设置提示消息
// 根据状态设置提示消息
setSnackbarMessage(data.info || '操作成功');
setSnackbarOpen(true);
} catch (error) {
// 错误处理
console.error('API call failed:', error);
setResponse(`Error: ${error.message}`);
setSnackbarMessage(`错误: ${error.message}`);
setSnackbarOpen(true);