本文档提供如何从前端(Web 或其他客户端)直接调用本地或远程服务的示例。
首先确保服务端已经启动:
# 在项目根目录
npm run dev
# 或
bun server.ts
假设服务运行在 http://localhost:10003 (根据 config.json 或默认端口)。
您可以在终端中使用 curl 命令直接测试接口。
curl "http://localhost:10003/api/tikhub/search?keyword=elonmusk"
curl "http://localhost:10003/api/tikhub/users/elonmusk"
# 注意替换 secUid 为实际值
curl "http://localhost:10003/api/tikhub/users/MS4wLjABAAAA.../posts?count=10"
# 注意替换 videoId 为实际值
curl "http://localhost:10003/api/tikhub/posts/7281234567890/comments"
在您的前端代码(Vue, React, Angular 等)中,可以直接使用 fetch 或 axios 调用。
// 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();
}
};
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);
}
}
server.ts 中可能需要添加 cors 包)。3000 或 10003,请检查服务端启动日志。