Hono 框架参考

Hono — 超快边缘优先 TypeScript Web 框架,支持 Cloudflare Workers、Deno、Bun、Node.js 和 Vercel Edge。

1. 路由

import { Hono } from 'hono'

const app = new Hono()

app.get('/', (c) => c.text('Hello Hono!'))
app.post('/articles', createArticle)
app.put('/articles/:id', updateArticle)
app.delete('/articles/:id', deleteArticle)

app.get('/articles/:id', (c) => {
  const id = c.req.param('id')
  return c.json({ id })
})

export default app

2. 中间件

import { cors } from 'hono/cors'
import { logger } from 'hono/logger'
import { secureHeaders } from 'hono/secure-headers'

app.use('*', logger())
app.use('*', cors({
  origin: ['https://app.example.com'],
  allowMethods: ['GET', 'POST', 'PUT', 'DELETE'],
  credentials: true,
}))
app.use('*', secureHeaders())

// 自定义中间件
app.use('*', async (c, next) => {
  const start = Date.now()
  await next()
  c.header('X-Response-Time', `${Date.now() - start}ms`)
})

3. Zod 验证

import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'

const createSchema = z.object({
  title:   z.string().min(5).max(300),
  content: z.string().min(50),
  status:  z.enum(['draft', 'published']).default('draft'),
})

app.post('/articles', zValidator('json', createSchema), async (c) => {
  const data = c.req.valid('json')  // 完全类型化
  return c.json(await db.create(data), 201)
})

4. RPC 客户端

// 服务端 — 定义类型化路由
const route = new Hono()
  .get('/', (c) => c.json({ articles: [] }))
  .post('/', zValidator('json', createSchema), async (c) => {
    const body = c.req.valid('json')
    return c.json({ id: '1', ...body }, 201)
  })

export type AppType = typeof route

// 客户端 — 完全类型安全
import { hc } from 'hono/client'
import type { AppType } from './server'

const client = hc<AppType>('http://localhost:3000')
const res = await client.articles.$get()
const articles = await res.json()  // 有类型提示

5. 部署目标

平台入口说明
Cloudflare Workersexport default app默认,最快
Bunexport default { port, fetch: app.fetch }原生 Bun 服务
DenoDeno.serve(app.fetch)Deno Deploy
Node.jsserve(app) from @hono/node-serverNode 兼容层
Vercel Edgeexport const GET = handle(app)Vercel Edge Runtime