Files
ColaFlow/API_CONNECTION_FIX_SUMMARY.md
Yaojia Wang 24fb646739 docs: Add API connection debugging documentation and progress update
Added comprehensive debugging tools and documentation for API connection issues.

Changes:
- Created test-api-connection.sh - Automated diagnostic script
- Created DEBUGGING_GUIDE.md - Step-by-step debugging guide
- Created API_CONNECTION_FIX_SUMMARY.md - Complete fix summary
- Updated progress.md with API connection debugging enhancement entry

These tools help diagnose and resolve frontend-backend connection issues.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
2025-11-03 09:15:54 +01:00

360 lines
9.2 KiB
Markdown
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 连接问题修复摘要
## 问题描述
**报告时间**: 2025-11-03
**问题**: 前端项目列表页面无法显示项目数据
### 症状
1. 前端正常运行在 http://localhost:3000
2. 页面渲染正常GET /projects 200
3. 但是后端 API 无法连接curl localhost:5167 连接失败)
## 诊断结果
运行诊断测试脚本后发现:
```bash
./test-api-connection.sh
```
### 关键发现:
1. ✗ 后端服务器未在端口 5167 运行
2. ✗ API 健康检查端点无法访问
3. ✗ Projects 端点无法访问
4. ⚠ 前端运行中但返回 307 状态码(重定向)
5. ✓ .env.local 配置正确:`NEXT_PUBLIC_API_URL=http://localhost:5167/api/v1`
### 根本原因
**后端服务器未启动** - 这是主要问题
## 已实施的修复
### 1. 增强前端调试功能
#### 文件:`colaflow-web/lib/api/client.ts`
**修改内容**:
- 添加 API URL 初始化日志
- 为每个 API 请求添加详细日志
- 增强错误处理,捕获并记录网络错误
- 显示请求 URL、方法、状态码
**代码示例**:
```typescript
// 初始化时记录 API URL
if (typeof window !== 'undefined') {
console.log('[API Client] API_URL:', API_URL);
console.log('[API Client] NEXT_PUBLIC_API_URL:', process.env.NEXT_PUBLIC_API_URL);
}
// 请求前记录
console.log('[API Client] Request:', {
method: options.method || 'GET',
url,
endpoint,
});
// 捕获网络错误
try {
const response = await fetch(url, config);
const result = await handleResponse<T>(response);
console.log('[API Client] Response:', { url, status: response.status, data: result });
return result;
} catch (error) {
console.error('[API Client] Network error:', {
url,
error: error instanceof Error ? error.message : String(error),
errorObject: error,
});
throw error;
}
```
#### 文件:`colaflow-web/app/(dashboard)/projects/page.tsx`
**修改内容**:
- 将简单的错误消息替换为详细的错误卡片
- 显示错误详情、API URL、故障排查步骤
- 添加重试按钮
- 添加控制台调试日志
**功能**:
```typescript
if (error) {
const errorMessage = error instanceof Error ? error.message : 'Unknown error';
const apiUrl = process.env.NEXT_PUBLIC_API_URL || 'http://localhost:5000/api/v1';
console.error('[ProjectsPage] Error loading projects:', error);
return (
<Card>
<CardHeader>
<CardTitle>Failed to Load Projects</CardTitle>
<CardDescription>Unable to connect to the backend API</CardDescription>
</CardHeader>
<CardContent>
<div>Error Details: {errorMessage}</div>
<div>API URL: {apiUrl}</div>
<div>Troubleshooting Steps:
- Check if backend server is running
- Verify API URL in .env.local
- Check browser console (F12)
- Check network tab (F12)
</div>
<Button onClick={() => window.location.reload()}>Retry</Button>
</CardContent>
</Card>
);
}
```
#### 文件:`colaflow-web/lib/hooks/use-projects.ts`
**修改内容**:
- 在 queryFn 中添加详细日志
- 记录请求开始、成功、失败
- 减少重试次数从 3 降至 1更快失败
**代码**:
```typescript
export function useProjects(page = 1, pageSize = 20) {
return useQuery<Project[]>({
queryKey: ['projects', page, pageSize],
queryFn: async () => {
console.log('[useProjects] Fetching projects...', { page, pageSize });
try {
const result = await projectsApi.getAll(page, pageSize);
console.log('[useProjects] Fetch successful:', result);
return result;
} catch (error) {
console.error('[useProjects] Fetch failed:', error);
throw error;
}
},
staleTime: 5 * 60 * 1000,
retry: 1, // Fail faster
});
}
```
### 2. 创建诊断工具
#### 文件:`test-api-connection.sh`
**功能**:
- 检查后端是否在端口 5167 运行
- 测试 API 健康检查端点
- 测试 Projects 端点
- 检查前端是否运行
- 验证 .env.local 配置
- 提供彩色输出和清晰的下一步指令
#### 文件:`DEBUGGING_GUIDE.md`
**内容**:
- 详细的诊断步骤
- 常见问题及解决方案
- 如何使用浏览器开发工具
- 日志输出示例
- 验证修复的检查清单
## 解决方案
### 立即行动:启动后端服务器
```bash
# 方法 1: 使用 .NET CLI
cd colaflow-api/src/ColaFlow.API
dotnet run
# 方法 2: 使用解决方案
cd colaflow-api
dotnet run --project src/ColaFlow.API/ColaFlow.API.csproj
# 验证后端运行
curl http://localhost:5167/api/v1/health
curl http://localhost:5167/api/v1/projects
```
### 验证步骤
1. **启动后端**
```bash
cd colaflow-api/src/ColaFlow.API
dotnet run
```
期望输出:`Now listening on: http://localhost:5167`
2. **确认前端运行**
```bash
cd colaflow-web
npm run dev
```
期望输出:`Ready on http://localhost:3000`
3. **运行诊断测试**
```bash
./test-api-connection.sh
```
期望:所有测试显示 ✓ 绿色通过
4. **访问项目页面**
- 打开 http://localhost:3000/projects
- 按 F12 打开开发者工具
- 查看 Console 标签页
5. **检查控制台日志**
期望看到:
```
[API Client] API_URL: http://localhost:5167/api/v1
[useProjects] Fetching projects...
[API Client] Request: GET http://localhost:5167/api/v1/projects...
[API Client] Response: {status: 200, data: [...]}
[useProjects] Fetch successful
```
6. **检查网络请求**
- 切换到 Network 标签页
- 查找 `projects?page=1&pageSize=20` 请求
- 状态应为 200 OK
## Git 提交
### Commit 1: 前端调试增强
```
fix(frontend): Add comprehensive debugging for API connection issues
Enhanced error handling and debugging to diagnose API connection problems.
Changes:
- Added detailed console logging in API client (client.ts)
- Enhanced error display in projects page with troubleshooting steps
- Added logging in useProjects hook for better debugging
- Display API URL and error details on error screen
- Added retry button for easy error recovery
Files changed:
- colaflow-web/lib/api/client.ts
- colaflow-web/lib/hooks/use-projects.ts
- colaflow-web/app/(dashboard)/projects/page.tsx
Commit: 2ea3c93
```
## 预期结果
### 修复前(当前状态)
- 页面显示:`Failed to load projects. Please try again later.`
- 控制台:无详细错误信息
- 无法判断问题原因
### 修复后(启动后端后)
- 页面显示:项目列表或"No projects yet"消息
- 控制台:详细的请求/响应日志
- 网络面板200 OK 状态码
- 能够创建、查看、编辑项目
### 如果后端仍未启动
- 页面显示:详细的错误卡片,包含:
- 错误消息:`Failed to fetch` 或 `Network request failed`
- API URL`http://localhost:5167/api/v1`
- 故障排查步骤
- 重试按钮
- 控制台:完整的调试日志
- 网络面板:失败的请求(红色)
## 后续优化建议
### 1. 添加 API 健康检查
在应用启动时检查后端是否可用:
```typescript
// useHealthCheck.ts
export function useHealthCheck() {
return useQuery({
queryKey: ['health'],
queryFn: () => api.get('/health'),
refetchInterval: 30000, // 30秒检查一次
});
}
```
### 2. 添加全局错误处理
使用 React Error Boundary 捕获 API 错误:
```typescript
// ErrorBoundary.tsx
export class ApiErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError(error) {
return { hasError: true };
}
render() {
if (this.state.hasError) {
return <ApiErrorPage />;
}
return this.props.children;
}
}
```
### 3. 添加重连逻辑
实现指数退避重试:
```typescript
const queryClient = new QueryClient({
defaultOptions: {
queries: {
retry: 3,
retryDelay: (attemptIndex) => Math.min(1000 * 2 ** attemptIndex, 30000),
},
},
});
```
### 4. 添加离线检测
检测网络状态并显示离线提示:
```typescript
export function useOnlineStatus() {
const [isOnline, setIsOnline] = useState(navigator.onLine);
useEffect(() => {
const handleOnline = () => setIsOnline(true);
const handleOffline = () => setIsOnline(false);
window.addEventListener('online', handleOnline);
window.addEventListener('offline', handleOffline);
return () => {
window.removeEventListener('online', handleOnline);
window.removeEventListener('offline', handleOffline);
};
}, []);
return isOnline;
}
```
### 5. 生产环境优化
移除调试日志或使用日志级别:
```typescript
const DEBUG = process.env.NODE_ENV === 'development';
if (DEBUG) {
console.log('[API Client] Request:', ...);
}
```
## 相关文档
- `DEBUGGING_GUIDE.md` - 详细的调试指南
- `test-api-connection.sh` - API 连接诊断脚本
- `colaflow-api/README.md` - 后端启动指南
- `colaflow-web/README.md` - 前端配置指南
## 联系信息
如果问题持续存在,请提供以下信息:
1. 浏览器控制台完整日志Console 标签)
2. 网络请求详情Network 标签)
3. 后端控制台输出
4. `.env.local` 文件内容
5. 诊断脚本输出:`./test-api-connection.sh`
---
**状态**: ✓ 前端调试增强完成,等待后端启动验证
**下一步**: 启动后端服务器并验证修复效果