vanilla-ts-http-route-handler
它能做什么
这个技能说明如何在使用内置 http 模块和 switch 路由器的 Node 服务器中添加 API 路由。适合开发小型 TypeScript 服务器的开发者。
适用场景
- ✓当你的服务器使用内置的 http 模块,而你需要新增一个路由时。
- ✓当你希望不为小型服务器引入 Express 或其他框架时。
- ✓当其他路由文件使用的框架风格与你的服务器不匹配时。
技能链接
https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/vanilla-ts-http-route-handler/SKILL.md复制后粘贴给你的 AI(Claude、ChatGPT 或 Cursor),让它按照说明操作。
使用方法
最简单的方法:复制下面的消息,粘贴给你的 AI。它会读取这个技能并按说明操作。
可直接粘贴的消息
适用于 Claude Code、Codex 或 Cursor:在项目文件夹中运行,即可安装该技能。
下载 SKILL.md,放进智能体的技能文件夹。
可以这样问 AI
“请帮我在 Node 服务器中添加一个新的健康检查路由,不需要安装 Express。”
每周 5 个新技能,1 分钟读完。
工作原理
智能体创建一个路由文件,使用内置的请求和响应类型,然后在服务器的 switch 语句中注册该路由。
技术内容(原始 SKILL.md)
作者在 GitHub 上的英文原文。
Adding Route Handlers to a Vanilla TypeScript HTTP Server
Use this skill whenever you need to add a new route to a TypeScript project
that uses Node's built-in http module and a switch/case pathname router
without Express or Next.js.
Step 0 — Confirm the routing style
Before writing any code, inspect server/index.ts (or whichever file starts
the HTTP server). Look for:
http.createServer((req, res) => {
const { pathname } = new URL(req.url!, `http://${req.headers.host}`);
switch (pathname) {
case '/api/foo': ...
}
});
If you see this pattern, follow the steps below.
Do NOT use express.Router, next/server, or any framework-specific
handler signature — even if other files in server/routes/ happen to
use those patterns.
Step 1 — Create the route file
Create server/routes/<feature>.ts.
Use only the native Node types: http.IncomingMessage and
http.ServerResponse.
// server/routes/health.ts
import http from 'http';
export async function handleHealth(
req: http.IncomingMessage,
res: http.ServerResponse
): Promise<void> {
// Parse body for POST/PUT if needed
const body = await readBody(req); // helper shown in Step 3
res.writeHead(200, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ status: 'ok' }));
}
Rules for the route file:
- Export the handler as a named async function (
handle<Feature>). - Accept exactly
(req: http.IncomingMessage, res: http.ServerResponse). - Return
Promise<void>. - Do not call
next()or return aResponseobject. - Handle errors internally and write an appropriate HTTP status + JSON body.
Step 2 — Import the handler in server/index.ts
Add a named import at the top of the file alongside any existing imports:
import { handleHealth } from './routes/health';
Step 3 — Add a case entry to the switch block
Locate the existing switch (pathname) block and add a new case:
switch (pathname) {
case '/api/health':
await handleHealth(req, res);
break;
// … existing cases …
default:
res.writeHead(404, { 'Content-Type': 'application/json' });
res.end(JSON.stringify({ error: 'Not found' }));
}
- Match the exact pathname string used by the client.
- Always
break(orreturn) after calling the handler. - Keep the
defaultcase last.
Step 4 — Optional: shared body-reading helper
If multiple routes need to parse a JSON request body, add a small utility rather than duplicating the logic:
// server/utils/readBody.ts
import http from 'http';
export function readBody(req: http.IncomingMessage): Promise<unknown> {
return new Promise((resolve, reject) => {
let data = '';
req.on('data', (chunk) => (data += chunk));
req.on('end', () => {
try {
resolve(data ? JSON.parse(data) : {});
} catch {
reject(new Error('Invalid JSON'));
}
});
req.on('error', reject);
});
}
Import and use it inside any route handler that needs it.
Checklist
-
server/routes/<feature>.tsexists and exports a named async handler. - Handler signature is
(req: http.IncomingMessage, res: http.ServerResponse): Promise<void>. - Handler always calls
res.writeHead(...)andres.end(...)on every code path. - Handler is imported in
server/index.ts. - A matching
caseentry is present in theswitch (pathname)block. - No Express / Next.js / Koa types or patterns were introduced.
Anti-patterns to avoid
| ❌ Wrong | ✅ Correct |
|---|---|
import { Router } from 'express' |
import http from 'http' |
export default function handler(req: NextApiRequest, ...) |
export async function handleFoo(req: http.IncomingMessage, ...) |
router.get('/foo', ...) |
case '/api/foo': await handleFoo(req, res); break; |
| Returning a value from the handler | Calling res.end(...) and returning void |
常见问题
为什么不使用 Express?
这个技能适用于已经使用原生 Node 的服务器。添加 Express 会改变整个服务器的运作方式。
我怎么知道我的服务器使用哪种风格?
技能会告诉你检查主服务器文件中是否有针对请求路径的 switch 语句。
路由可以读取请求体吗?
可以。技能包含一个辅助函数,可以为 POST 和 PUT 请求读取请求体。
详情
作者的原始描述
How to correctly add route handlers in a vanilla TypeScript project that uses http.createServer with a manual switch/case router — without introducing Express Router or Next.js patterns.
repo: HKUDS/AgentPilot
热度
- GitHub 星标
- 7.8k
- 排名
- #13088
- 许可证
- MIT
- 更新时间
- 2026/11/1
评论
- …
同一仓库的更多技能
agentpilot
7.8k帮你的智能体准备任务并运行 AgentPilot 循环,逐步改进项目:循环会提出修改、测试修改并为其打分。
openspace
7.8k帮你的智能体设置 OpenSpace,这是一个用于存储和获取智能体技能的工具,并通过 MCP 将其连接到你的 AI 应用。
rsi-arena
7.8k帮你的智能体设置并运行标准 AI 基准测试,例如 AIME 和 Terminal-Bench,用来比较不同的改进方法。
experiment-guide
7.8k帮你的智能体规划小型实验、阅读实验结果并记录发现,同时研究如何改进一个程序。