
关于
使用 Hono 构建超快 Web API 和全栈应用——可运行在 Cloudflare Workers、Deno、Bun、Node.js 及任何 WinterCG 兼容运行时。
name: hono description: "使用 Hono 构建超快 Web API 和全栈应用——运行在 Cloudflare Workers、Deno、Bun、Node.js 和任何 WinterCG 兼容运行时上。" category: backend risk: safe source: community date_added: "2026-03-18" author: suhaibjanjua tags: [hono, edge, cloudflare-workers, bun, deno, api, typescript, web-standards] tools: [claude, cursor, gemini]
Hono Web 框架
概述
Hono(炎,日语中的"火焰")是基于 Web 标准(Request/Response/fetch)构建的小型超快 Web 框架。它可以在任何地方运行:Cloudflare Workers、Deno Deploy、Bun、Node.js、AWS Lambda 和任何 WinterCG 兼容运行时——使用相同的代码。Hono 的路由器是最快的之一,其中间件系统、内置 JSX 支持和 RPC 客户端使其成为边缘 API、BFF 和轻量级全栈应用的强力选择。
何时使用此技能
- 为边缘部署构建 REST 或 RPC API 时(Cloudflare Workers、Deno Deploy)
- 需要 Bun 或 Node.js 的最小但类型安全的服务器框架时
- 构建低延迟要求的 Backend for Frontend(BFF)层时
- 从 Express 迁移但想要更好的 TypeScript 支持和边缘兼容性时
- 用户询问 Hono 路由、中间件、
c.req、c.json或hc()RPC 客户端时
工作原理
步骤 1:项目设置
Cloudflare Workers(推荐用于边缘):
npm create hono@latest my-api
# Select: cloudflare-workers
cd my-api
npm install
npm run dev # Wrangler local dev
npm run deploy # Deploy to Cloudflare
Bun / Node.js:
mkdir my-api && cd my-api
bun init
bun add hono
// src/index.ts (Bun)
import { Hono } from 'hono';
const app = new Hono();
app.get('/', c => c.text('Hello Hono!'));
export default {
port: 3000,
fetch: app.fetch,
};
步骤 2:路由
import { Hono } from 'hono';
const app = new Hono();
// Basic methods
app.get('/posts', c => c.json({ posts: [] }));
app.post('/posts', c => c.json({ created: true }, 201));
app.put('/posts/:id', c => c.json({ updated: true }));
app.delete('/posts/:id', c => c.json({ deleted: true }));
// Route params and query strings
app.get('/posts/:id', async c => {
const id = c.req.param('id');
const format = c.req.query('format') ?? 'json';
return c.json({ id, format });
});
// Wildcard
app.get('/static/*', c => c.text('static file'));
export default app;
链式路由:
app
.get('/users', listUsers)
.post('/users', createUser)
.get('/users/:id', getUser)
.patch('/users/:id', updateUser)
.delete('/users/:id', deleteUser);
步骤 3:中间件
Hono 中间件的工作方式与 fetch 拦截器完全相同——处理前后:
import { Hono } from 'hono';
import { logger } from 'hono/logger';
import { cors } from 'hono/cors';
import { bearerAuth } from 'hono/bearer-auth';
const app = new Hono();
// Built-in middleware
app.use('*', logger());
app.use('/api/*', cors({ origin: 'https://myapp.com' }));
app.use('/api/admin/*', bearerAuth({ token: process.env.API_TOKEN! }));
// Custom middleware
app.use('*', async (c, next) => {
c.set('requestId', crypto.randomUUID());
await next();
c.header('X-Request-Id', c.get('requestId'));
});
可用内置中间件: logger、cors、csrf、etag、cache、basicAuth、bearerAuth、jwt、compress、bodyLimit、timeout、prettyJSON、secureHeaders。
步骤 4:请求和响应辅助
app.post('/submit', async c => {
// Parse body
const body = await c.req.json<{ name: string; email: string }>();
const form = await c.req.formData();
const text = await c.req.text();
// Headers and cookies
const auth = c.req.header('authorization');
const token = getCookie(c, 'session');
// Responses
return c.json({ ok: true }); // JSON
return c.text('hello'); // Plain text
return c.html('<h1>Hello</h1>'); // HTML
return c.redirect('/login'); // Redirect
return c.notFound(); // 404
});
兼容工具
Claude CodeCursor
标签
后端开发
