# Frontend V2 - Next.js 14 + SuperJSON 基于 Next.js 14 App Router 构建的前端应用,使用 SuperJSON 实现 JSON 序列化/反序列化。 ## 技术栈 - **Next.js 14.2** - App Router + Server Components - **React 18** - Concurrent Features - **TypeScript** - 类型安全 - **Tailwind CSS** - 样式框架 - **SuperJSON** - JSON 序列化增强 - **自定义 Hooks** - 数据获取和状态管理 ## 项目结构 ``` frontend-v2/ ├── app/ # Next.js App Router │ ├── auth/ # 认证页面 │ │ └── page.tsx │ ├── layout.tsx # 根布局 │ ├── page.tsx # 主页(聊天界面) │ └── globals.css # 全局样式 ├── components/ # React 组件 │ ├── Header.tsx # 页面头部 │ ├── ChatInput.tsx # 聊天输入 │ ├── ChatMessage.tsx # 聊天消息 │ └── ToolCallPanel.tsx # 工具调用面板 ├── lib/ # 工具库 │ ├── api-client.ts # API 客户端 │ ├── superjson.ts # SuperJSON 配置 │ ├── react-query.tsx # React Query 配置 │ └── hooks.ts # 自定义 Hooks ├── public/ # 静态资源 ├── package.json ├── tsconfig.json ├── tailwind.config.ts ├── next.config.js └── README.md ``` ## 安装依赖 ```bash cd frontend-v2 npm install # 或 pnpm install # 或 yarn install ``` ## 配置环境变量 复制 `.env.local.example` 为 `.env.local`: ```bash cp .env.local.example .env.local ``` 编辑 `.env.local`,配置后端 API 地址: ```env BACKEND_URL=http://localhost:8080 ``` ## 启动开发服务器 ```bash npm run dev ``` 应用将在 `http://localhost:3000` 启动。 ## 构建生产版本 ```bash npm run build npm start ``` ## API 集成 ### 后端端点 | 端点 | 方法 | 说明 | |------|------|------| | `/api/health` | GET | 健康检查 | | `/api/chat` | POST | 聊天(非流式)| | `/api/chat/stream` | POST | 聊天(SSE 流式)| | `/api/mcp/servers` | GET | MCP 服务器列表 | | `/api/mcp/tools` | GET | MCP 工具列表 | | `/api/auth/login` | POST | 用户登录 | | `/api/auth/register` | POST | 用户注册 | | `/api/auth/status` | GET | 认证状态 | ### 使用 API 客户端 ```typescript import { apiClient } from '@/lib/api-client'; // 发送聊天消息 const response = await apiClient.chat('你好', []); // 登录 const result = await apiClient.login('user@example.com', 'password'); // 获取 MCP 工具列表 const tools = await apiClient.listMcpTools(); ``` ### 使用自定义 Hooks ```typescript import { useChat, useAuth } from '@/lib/hooks'; function ChatComponent() { const { sendMessage, isLoading, response } = useChat(); const { login, logout, isAuthenticated } = useAuth(); // 发送消息 const handleSend = () => { sendMessage('你好 AI', []); }; return ( // ... ); } ``` ## JSON 序列化 (SuperJSON) SuperJSON 用于处理 Next.js Server Components 和 Client Components 之间的数据传输,支持: - Date 对象 - undefined - Set/Map - Error 对象 - 自定义类实例 ```typescript import { serialize, deserialize } from '@/lib/superjson'; // 序列化 const json = serialize(data); // 反序列化 const data = deserialize(json); ``` ## 外网访问 如果需要通过外网访问后端 API,请配置 `.env.local`: ```env BACKEND_URL=https://d8d-ai-vscode-8080-{workspace_id}-{item_id}-template-6-group.dev.d8d.fun ``` ## 开发说明 1. 端口配置:Next.js 默认使用 3000 端口,可在 `package.json` 中修改 2. API 代理:开发环境通过 `next.config.js` 的 `rewrites` 配置代理 3. 类型定义:所有 API 请求/响应都有完整的 TypeScript 类型定义