Hono框架指南

快速入门

npm create hono@latest my-app // src/index.ts import { Hono } from 'hono' import { cors } from 'hono/cors' import { logger } from 'hono/logger' import { zValidator } from '@hono/zod-validator' import { z } from 'zod' const app = new Hono() app.use('*', logger()) app.use('/api/*', cors()) // 带验证的路由 const schema = z.object({ name: z.string().min(2) }) app.post('/users', zValidator('json', schema), async (c) => { const { name } = c.req.valid('json') return c.json({ id: 1, name }, 201) }) export default app

路由和上下文

// 路径参数和查询参数 app.get('/users/:id', (c) => { const id = c.req.param('id') const page = c.req.query('page') ?? '1' return c.json({ id, page }) }) // 路由分组 const api = new Hono().basePath('/api') api.get('/health', (c) => c.json({ ok: true })) app.route('/', api) // Middleware with context app.use('*', async (c, next) => { c.set('requestId', crypto.randomUUID()) await next() c.header('X-Request-ID', c.get('requestId')) })

运行时支持

运行时适配器
Cloudflare Workers原生(默认)
Bunhono/bun
Denohono/deno
Node.js@hono/node-server
AWS Lambdahono/aws-lambda
Vercelhono/vercel