跳到主要内容

路由与请求

路由怎么注册、按什么顺序匹配?​

  • 标准方法: app.get/post/put/delete;
  • 其他场景: app.on(method, path, ...) 管自定义方法、多方法与多路径;
  • 顺序: 按注册顺序匹配;
  • 陷阱: app.get("*") 写在前面会吞掉后面所有路由;
  • 做法: 兜底放最后;
const app = new Hono();

app.get("/", (c) => c.text("GET /"));
app.all("/any", (c) => c.text("任意方法"));
app.on("GET", ["/hello", "/ja/hello"], (c) => c.text("两条路径"));
app.get("/wild/*/card", (c) => c.text("通配符"));
  • 链式写法: 只有 .get(...).post(...) 这样注册, AppType 才能完整推理;
  • 依赖方: RPC 与 testClient, 见 004;

路径参数与通配符怎么匹配?​

写法匹配读取
/user/:name/user/张三c.req.param("name")
/api/animal/:type?可省略该段可能是 undefined
/post/:date{[0-9]+}只匹配数字同上
/p/:f{.+\.png}允许多段与点号同上
*任意路径—
  • 正则段写在 {} 里且必须匹配整段; 参数默认不含斜杠, 要吞斜杠写 :id{.+};
  • 严格模式: 默认开启, /hello 不等于 /hello/;
  • 关闭: new Hono({ strict: false });
  • HEAD: 按 GET 匹配后丢弃响应体;

子路由怎么挂?​

// routes/book.ts
const book = new Hono()
.get("/", (c) => c.text("List Books"))
.get("/:id", (c) => c.text(c.req.param("id")));

// app.ts
const app = new Hono().route("/book", book); // GET /book、GET /book/:id
  • 挂载: app.route(prefix, sub) 把子应用挂到前缀下, 子应用里写相对路径;
  • 子应用前缀: new Hono().basePath("/api");
  • 适用: 要独立运行或测试的子应用;
  • 再挂到根: app.route("/", api);
  • 陷阱: route() 只拷贝当时已有的路由, 之后加的路由不同步;
  • 规则: 先装配, 最后挂载, 否则表现为 404 且不报错;
  • 排查 404: 先用 npx hono routes 看实际路由表;

请求里的值怎么读?​

app.get("/entry/:id", (c) => {
const id = c.req.param("id");
const q = c.req.query("q"); // 缺失是 undefined,不是 ""
const tags = c.req.queries("tags"); // ?tags=A&tags=B → ["A","B"]
const ua = c.req.header("user-agent"); // 大小写不敏感
return c.json({ id, q, tags, ua, path: c.req.path });
});
  • 类型: 查询值一律 string;
  • 取全部请求头时键全是小写, headers["X-Foo"] 永远取不到;
  • 读取: c.req.json()、parseBody()、text()、formData(), 只能读一次;
  • json() 遇非法 JSON: 抛错变成 500;
  • 要 400: 用校验器;
  • 一次性流: 校验器读过后 c.req.raw 已耗尽;
  • 需要原文: 用 cloneRawRequest(c.req), 来自 hono/request;