Hono 边缘框架
一句话概述:Hono 是 2025-2026 年最火的 TypeScript Web 框架,基于 Web 标准 API 构建,14KB 大小、零依赖,同一份代码可在 Cloudflare Workers、Deno、Bun、Node.js 等任何运行时运行。
核心知识点
| 概念 | 白话解释 |
|---|
| Web Standards | Web 标准 = 基于 Fetch API 等浏览器标准,不绑定任何运行时 |
| Edge Computing | 边缘计算 = 代码在离用户最近的服务器运行(全球 CDN 节点) |
| Multi-runtime | 多运行时 = 同一份代码在 Node.js、Deno、Bun、Workers 都能跑 |
| RPC Client | RPC 客户端 = 自动生成带类型的前端 API 客户端 |
| Middleware | 中间件 = 和 Express 类似的请求处理链 |
| Validator | 验证器 = 内置请求数据验证 |
安装配置
# 创建新项目(Cloudflare Workers)
npm create hono@latest my-app # 交互式选择运行时
# 手动安装
npm install hono # 安装 Hono
# 各运行时的入口
# Node.js: @hono/node-server
# Bun: 直接用
# Deno: 直接用
# Workers: wrangler
基本使用
// src/index.ts
import { Hono } from 'hono'
import { cors } from 'hono/cors' // 内置 CORS 中间件
import { logger } from 'hono/logger' // 内置日志中间件
import { validator } from 'hono/validator' // 内置验证器
const app = new Hono()
// 中间件
app.use('*', logger()) // 全局日志
app.use('/api/*', cors()) // API 跨域
// 基本路由
app.get('/', (c) => {
return c.json({ message: 'Hello Hono!' }) // 返回 JSON
})
// 路径参数
app.get('/api/samples/:id', (c) => {
const id = c.req.param('id') // 获取路径参数
return c.json({ id })
})
// 查询参数
app.get('/api/samples', (c) => {
const page = c.req.query('page') || '1' // 获取查询参数
return c.json({ page, data: [] })
})
// POST + 验证
app.post('/api/samples',
validator('json', (value, c) => { // 请求体验证
const { name, species } = value
if (!name || !species) {
return c.json({ error: 'name and species are required' }, 400)
}
return { name: String(name), species: String(species) }
}),
(c) => {
const data = c.req.valid('json') // 获取验证过的数据
return c.json({ id: 1, ...data }, 201)
}
)
export default app // 导出(Cloudflare Workers/Bun 等使用)
// Node.js 入口
import { serve } from '@hono/node-server'
import app from './index'
serve({ fetch: app.fetch, port: 3000 })
路由组
const api = new Hono()
api.get('/users', (c) => c.json([]))
api.get('/users/:id', (c) => c.json({ id: c.req.param('id') }))
app.route('/api/v1', api) // 挂载到 /api/v1
高级用法
1. RPC 模式(类型安全的前后端通信)
// server.ts
import { Hono } from 'hono'
import { hc } from 'hono/client'
const app = new Hono()
.get('/api/users', (c) => c.json([{ id: 1, name: 'Alice' }]))
.post('/api/users', async (c) => {
const body = await c.req.json()
return c.json({ id: 2, ...body }, 201)
})
export type AppType = typeof app // 导出类型
// client.ts(前端代码)
import { hc } from 'hono/client'
import type { AppType } from './server'
const client = hc<AppType>('http://localhost:3000')
const res = await client.api.users.$get() // 自动补全、类型安全
const users = await res.json()
2. 中间件开发
import { createMiddleware } from 'hono/factory'
const authMiddleware = createMiddleware(async (c, next) => {
const token = c.req.header('Authorization')?.replace('Bearer ', '')
if (!token) {
return c.json({ error: 'Unauthorized' }, 401)
}
c.set('userId', 'user-123') // 存储到上下文
await next()
})
app.use('/api/protected/*', authMiddleware)
3. Zod 验证集成
import { zValidator } from '@hono/zod-validator'
import { z } from 'zod'
const schema = z.object({
name: z.string().min(3),
email: z.string().email(),
})
app.post('/api/users', zValidator('json', schema), (c) => {
const data = c.req.valid('json') // 完全类型安全
return c.json(data, 201)
})
4. JSX 支持
import { Hono } from 'hono'
import { html } from 'hono/html'
app.get('/page', (c) => {
return c.html(
<html>
<body><h1>Hello from Hono JSX!</h1></body>
</html>
)
})
常见报错
| 报错信息 | 原因 | 解决方法 |
|---|
404 Not Found | 路由不匹配 | 检查路径和 HTTP 方法 |
TypeError: Failed to fetch | 前端跨域问题 | 添加 CORS 中间件 |
ReferenceError: process is not defined | 在 Workers/Edge 环境用了 Node.js API | 用 Web 标准 API 替代 |
Validation failed | 请求数据格式错误 | 检查验证规则和请求数据 |
速查表
// === 请求数据 ===
c.req.param('id') // 路径参数
c.req.query('page') // 查询参数
c.req.header('Auth') // 请求头
await c.req.json() // JSON 请求体
await c.req.formData() // 表单数据
c.req.valid('json') // 验证后的数据
// === 响应 ===
c.json(data) // JSON
c.json(data, 201) // 带状态码
c.text('hello') // 文本
c.html('<h1>Hi</h1>') // HTML
c.redirect('/url') // 重定向
c.notFound() // 404
// === 路由 ===
app.get('/path', handler)
app.post('/path', handler)
app.put('/path', handler)
app.delete('/path', handler)
app.all('/path', handler) // 所有方法
app.route('/prefix', sub) // 子路由
// === 内置中间件 ===
import { cors } from 'hono/cors'
import { logger } from 'hono/logger'
import { basicAuth } from 'hono/basic-auth'
import { jwt } from 'hono/jwt'
import { compress } from 'hono/compress'
import { cache } from 'hono/cache'
import { etag } from 'hono/etag'
// === 支持的运行时 ===
// Cloudflare Workers / Pages
// Deno / Deno Deploy
// Bun
// Node.js (@hono/node-server)
// AWS Lambda
// Vercel / Netlify
// Fastly Compute
参考:Hono 官网 | GitHub | 更新于 2026 年