路由

每个请求会匹配到一个(最具体的)路由处理器。

添加路由

你可以使用 H3.onH3.[method]H3.allH3 实例 注册路由处理器

路由器由 🌳 Rou3 提供支持,这是一款超快且体积小巧的路由匹配引擎。

示例: 注册一个路由,用于匹配 /hello 端点的 HTTP GET 请求。

  • 使用 H3.[method]
    app.get("/hello", () => "Hello world!");
    
  • 使用 H3.on
    app.on("GET", "/hello", () => "Hello world!");
    

你可以为同一路由注册多个不同方法的事件处理器:

app
  .get("/hello", () => "GET Hello world!")
  .post("/hello", () => "POST Hello world!")
  .any("/hello", () => "Any other method!");

你也可以使用 H3.all 方法注册一个允许接受任意 HTTP 方法的路由:

app.all("/hello", (event) => `This is a ${event.req.method} request!`);

动态路由

你可以通过 : 前缀定义动态路由参数:

// [GET] /hello/Bob => "Hello, Bob!"
app.get("/hello/:name", (event) => {
  return `Hello, ${event.context.params.name}!`;
});

你也可以使用 * 表示未命名的可选参数:

app.get("/hello/*", (event) => `Hello!`);

通配符路由

添加 /hello/:name 路由将匹配 /hello/world/hello/123,但不会匹配 /hello/foo/bar。 当你需要匹配多级子路由时,可以使用 ** 前缀:

app.get("/hello/**", (event) => `Hello ${event.context.params._}!`);

这将匹配 /hello/hello/world/hello/123/hello/world/123 等路径。

参数 _ 会以单个字符串的形式存储完整的通配符内容。

路由元数据

您可以在注册路由时定义可选的路由元数据,任何中间件都可以访问。

import { H3 } from "h3";

const app = new H3();

app.use((event) => {
  console.log(event.context.matchedRoute?.meta); // { auth: true }
});

app.get("/", (event) => "Hi!", { meta: { auth: true } });
在使用 defineHandler 对象语法定义路由时,也可以添加路由元信息。