# 示例:前端调用 TikHub 接口 本文档提供如何从前端(Web 或其他客户端)直接调用本地或远程服务的示例。 ## 1. 启动服务 首先确保服务端已经启动: ```bash # 在项目根目录 npm run dev # 或 bun server.ts ``` 假设服务运行在 `http://localhost:10003` (根据 config.json 或默认端口)。 ## 2. Curl 调用示例 您可以在终端中使用 `curl` 命令直接测试接口。 ### 搜索用户 ```bash curl "http://localhost:10003/api/tikhub/search?keyword=elonmusk" ``` ### 获取用户详情 ```bash curl "http://localhost:10003/api/tikhub/users/elonmusk" ``` ### 获取用户视频 ```bash # 注意替换 secUid 为实际值 curl "http://localhost:10003/api/tikhub/users/MS4wLjABAAAA.../posts?count=10" ``` ### 获取视频评论 ```bash # 注意替换 videoId 为实际值 curl "http://localhost:10003/api/tikhub/posts/7281234567890/comments" ``` ## 3. 前端 fetch 调用示例 在您的前端代码(Vue, React, Angular 等)中,可以直接使用 `fetch` 或 `axios` 调用。 ### 封装 API 服务类 (Frontend Service) ```typescript // frontend-api.ts const API_BASE_URL = 'http://localhost:10003/api/tikhub'; // 生产环境请替换为真实域名 export const TikHubApi = { /** * 搜索用户 */ async searchUsers(keyword: string) { const res = await fetch(`${API_BASE_URL}/search?keyword=${encodeURIComponent(keyword)}`); return res.json(); }, /** * 获取用户详情 */ async getUserProfile(uniqueId: string) { const res = await fetch(`${API_BASE_URL}/users/${uniqueId}`); return res.json(); }, /** * 获取用户作品 */ async getUserPosts(secUid: string, count = 20) { const res = await fetch(`${API_BASE_URL}/users/${secUid}/posts?count=${count}`); return res.json(); }, /** * 获取视频评论 */ async getPostComments(videoId: string, count = 50) { const res = await fetch(`${API_BASE_URL}/posts/${videoId}/comments?count=${count}`); return res.json(); } }; ``` ### 在组件中使用 ```typescript import { TikHubApi } from './frontend-api'; async function handleSearch() { try { const result = await TikHubApi.searchUsers('cat'); console.log('Search Results:', result.data); } catch (err) { console.error('Search failed:', err); } } ``` ## 4. 常见问题 - **CORS 跨域问题**: 如果前端和服务端不在同一个域,请确保服务端配置了 CORS 中间件(`server.ts` 中可能需要添加 `cors` 包)。 - **端口**: 默认端口可能为 `3000` 或 `10003`,请检查服务端启动日志。