跳到正文
Skillpedia
API 与服务器(后端)7.8k · #13088

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。它会读取这个技能并按说明操作。

可直接粘贴的消息

请用这个技能帮我:https://github.com/HKUDS/AgentPilot/blob/main/openspace/legacy/v1/showcase/skills/vanilla-ts-http-route-handler/SKILL.md 阅读该链接中的 SKILL.md 文件,并在我的任务中按照它的说明来做。
想让你的 AI 自己找到这样的技能吗?安装免费的 Skillpedia MCP:只需一行,每次任务前它都会在 15,000+ 个技能中搜索。1 分钟完成安装 →

可以这样问 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 a Response object.
  • 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 (or return) after calling the handler.
  • Keep the default case 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>.ts exists and exports a named async handler.
  • Handler signature is (req: http.IncomingMessage, res: http.ServerResponse): Promise<void>.
  • Handler always calls res.writeHead(...) and res.end(...) on every code path.
  • Handler is imported in server/index.ts.
  • A matching case entry is present in the switch (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

这个技能有用吗?

0

登录 后即可投票。

评论

  • …

同一仓库的更多技能

相似技能