本文档介绍如何测试 svc-code 项目的后端API接口。
项目采用 双路径调用架构:
src/api/): 供Vue页面使用,通过Vite代理src/test/): 独立测试使用,直接调用后端# 启动后端服务 (端口8020)
cd svc-code && go run main.go
# 启动前端开发服务器 (端口3000) - 可选
cd svc-code/web && npm run dev
在浏览器中打开: http://localhost:3000/test-api.html
或直接打开文件: svc-code/web/public/test-api.html
// 加载测试模块
import('./src/test/api-test-standalone.js').then(module => {
module.runAllTests();
});
// 或者使用全局对象(如果页面已加载)
testAPI.runAllTests();
# 测试健康检查
curl http://localhost:8020/api/health
# 测试项目列表
curl http://localhost:8020/api/projects
GET /api/health{ "success": true, "data": { "healthy": true, "version": "1.0" } }testAPI.testHealth()GET /api/projects{ "success": true, "data": [ ... ] } (包含3个模拟项目)testAPI.testProjects()src/api/)供Vue组件使用,通过Vite代理配置转发请求:
// 页面中使用
import { getProjects } from '@/api/project';
// 实际调用路径: /projects → 代理到 http://localhost:8020/api/projects
const projects = await getProjects();
src/test/api-test-standalone.ts)纯TypeScript模块,不依赖Vite配置,直接调用后端:
// 在浏览器控制台或Node.js中使用
import { testApi } from './src/test/api-test-standalone.js';
// 直接调用后端API
const projects = await testApi.getProjects();
主要功能:
runAllTests() - 运行所有测试testGetProjects() - 测试项目列表APItestHealthCheck() - 测试健康检查APItestBackendConnection() - 测试后端连接testApi - 直接API调用对象错误: NetworkError 或 Failed to fetch
解决方案:
lsof -i :8020错误: HTTP 404
解决方案:
/api/health, /api/projectsvite.config.ts)错误: Access-Control-Allow-Origin
解决方案:
错误: 无法解析JSON 或 success字段不正确
解决方案:
curl -v http://localhost:8020/api/health查看原始请求:
// 在浏览器控制台
fetch('http://localhost:8020/api/health')
.then(r => r.text())
.then(console.log);
检查网络请求:
打开浏览器开发者工具的Network标签页
查看请求详情和响应
后端日志:
查看后端终端输出
检查日志文件: svc-code/logs/
src/api/ 添加业务API模块src/test/api-test-standalone.ts 添加对应的测试函数public/test-api.html) 添加测试按钮// src/api/user.ts - 业务API
export const getUsers = () => request.get('/users');
// src/test/api-test-standalone.ts - 测试API
export const testGetUsers = async () => {
return testApi.get('/users');
};
src/api/project.ts - 项目API业务模块src/api/health.ts - 健康检查API业务模块src/test/api-test-standalone.ts - 独立测试模块public/test-api.html - 测试页面vite.config.ts - Vite代理配置