Skip to content

路由

文档:https://honodev.pages.dev/zh/docs/api/routing

路由解析器切换:https://honodev.pages.dev/zh/docs/api/presets

js
// HTTP 方法
app.get("/", (c) => c.text("GET /"));
app.post("/", (c) => c.text("POST /"));
app.put("/", (c) => c.text("PUT /"));
app.delete("/", (c) => c.text("DELETE /"));

// 通配符
app.get("/wild/*/card", (c) => {
  return c.text("GET /wild/*/card");
});

// 任意 HTTP 方法
app.all("/hello", (c) => c.text("Any Method /hello"));

// 自定义 HTTP 方法
app.on("PURGE", "/cache", (c) => c.text("PURGE Method /cache"));

// 多个方法
app.on(["PUT", "DELETE"], "/post", (c) => c.text("PUT or DELETE /post"));

// 多个路径
app.on("GET", ["/hello", "/ja/hello", "/en/hello"], (c) => c.text("Hello"));

路由分组

ts
// 注意名字是 book
const book = new Hono();

book.get("/", (c) => c.text("List Books")); // GET /book

book.get("/:id", (c) => {
  // GET /book/:id
  const id = c.req.param("id");
  return c.text("Get Book: " + id);
});

book.post("/", (c) => c.text("Create Book")); // POST /book
ts
const app = new Hono();
app.route("/book", book);

也可以这样

ts
const book = new Hono();
book.get("/book", (c) => c.text("List Books")); // GET /book
book.post("/book", (c) => c.text("Create Book")); // POST /book

// 注意这里有个 basePath!!!
const user = new Hono().basePath("/user");
user.get("/", (c) => c.text("List Users")); // GET /user
user.post("/", (c) => c.text("Create User")); // POST /user

const app = new Hono();
app.route("/", book); // 处理 /book
app.route("/", user); // 处理 /user

路由顺序

路由顺序非常重要

ts
app.get("/book/a", (c) => c.text("a")); // a
app.get("/book/:slug", (c) => c.text("common")); // common
GET /book/a ---> `a`
GET /book/b ---> `common`

* 会终止后续路由

ts
app.get("*", (c) => c.text("common")); // common
app.get("/foo", (c) => c.text("foo")); // foo
GET /foo ---> `common` // foo 将不会被调用

所以设置中间件时,需要注意顺序

404

js
import { Hono } from "hono";

const app = new Hono();

app.notFound((c) => {
  return c.text("自定义 404 消息", 404);
});

严格模式

默认为 true

/hello/hello/ 是不同的路由

js
new Hono({ strict: false });

关闭后 二者视为一个

路由模式

默认路由器是 SmartRouter

ts
import { RegExpRouter } from "hono/router/reg-exp-router";

const app = new Hono({ router: new RegExpRouter() });