今天热点榜开源项目第 2 名 Hono(TypeScript,68k star):一个小巧、超快的 Web 框架,能跑在各种 JavaScript 运行时上。这篇用 Node.js 跑它,一个文件 21 行,三个接口,全部实测。
一、总览:路由就是一张表

Hono 的核心就一张路由表:请求地址长什么样,就进哪个处理函数。三种取数据的方式一次讲清:固定文本、路径参数、查询参数。
路由表是核心:地址模式对上号,处理函数就接手。
二、三个接口
首页,返回固定文本:
app.get('/', (c) => c.text('Hello from Hono'))
路径参数:/hello/world 里的 world 就是 :name 的值:
app.get('/hello/:name', (c) => {
const name = c.req.param('name')
return c.json({ hello: name })
})
查询参数:/add?a=3&b=4 里的 a 和 b 从问号后面取:
app.get('/add', (c) => {
const a = Number(c.req.query('a'))
const b = Number(c.req.query('b'))
return c.json({ a, b, sum: a + b })
})
路径参数长在地址里,查询参数跟在问号后面,取法不一样,别混了。
三、跑起来:实测输出
环境:Node.js v24.22.1,hono 4.13.19。安装和启动只用三条命令:
npm init -y && npm pkg set type=module
npm install hono @hono/node-server
node app.js
启动后先看到这一行:
listening on http://127.0.0.1:18085
四个请求,实测输出一字不差:
$ curl http://127.0.0.1:18085/
Hello from Hono
$ curl http://127.0.0.1:18085/hello/world
{"hello":"world"}
$ curl "http://127.0.0.1:18085/add?a=3&b=4"
{"a":3,"b":4,"sum":7}
$ curl http://127.0.0.1:18085/missing
404 Not Found
三个接口都通了,没配的地址返回 404,符合预期。启动代码只有三行:
serve({ fetch: app.fetch, port: 18085 }, (info) => {
console.log(`listening on http://127.0.0.1:${info.port}`)
})
四、完整代码
21 行:
import { Hono } from 'hono'
import { serve } from '@hono/node-server'
const app = new Hono()
app.get('/', (c) => c.text('Hello from Hono'))
app.get('/hello/:name', (c) => {
const name = c.req.param('name')
return c.json({ hello: name })
})
app.get('/add', (c) => {
const a = Number(c.req.query('a'))
const b = Number(c.req.query('b'))
return c.json({ a, b, sum: a + b })
})
serve({ fetch: app.fetch, port: 18085 }, (info) => {
console.log(`listening on http://127.0.0.1:${info.port}`)
})
这篇的服务只绑了本机 127.0.0.1,学习演示用。想对外提供服务,得另外考虑部署和安全,别直接把演示服务挂到公网。
你还想看热点榜里的哪个项目?留言告诉我。
357




被折叠的 条评论
为什么被折叠?



