路由

¥Routing

每个请求都与一个(最具体的)路由处理程序匹配。

¥Each request is matched to one (most specific) route handler.

添加路由

¥Adding Routes

你可以使用 H3.onH3.[method]H3.all 将路由 handlers 注册到 H3 实例

¥You can register route handlers to H3 instance using H3.on, H3.[method], or H3.all.

Router 由 🌳 Rou3 提供支持,这是一款超快速且精简的路由匹配引擎。¥!TIP Router is powered by 🌳 Rou3, an ultra-fast and tiny route matcher engine.

示例:注册一个路由,将请求与 HTTP GET 方法的 /hello 端点匹配。

¥Example: Register a route to match requests to the /hello endpoint with HTTP GET method.

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

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

¥You can register multiple event handlers for the same route with different methods:

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

你还可以使用 H3.all 方法注册一个接受任何 HTTP 方法的路由:

¥You can also use H3.all method to register a route accepting any HTTP method:

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

动态路由

¥Dynamic Routes

你可以使用 : 前缀定义动态路由参数:

¥You can define dynamic route parameters using : prefix:

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

除了命名参数外,你还可以使用 * 作为未命名的可选参数:

¥Instead of named parameters, you can use * for unnamed optional parameters:

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

通配符路由

¥Wildcard Routes

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

¥Adding /hello/:name route will match /hello/world or /hello/123. But it will not match /hello/foo/bar. When you need to match multiple levels of sub routes, you can use ** prefix:

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

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

¥This will match /hello, /hello/world, /hello/123, /hello/world/123, etc.

参数 _ 将把完整的通配符内容存储为单个字符串。¥!NOTE Param _ will store the full wildcard content as a single string.

路由元数据

¥Route Meta

你可以在注册可选路由元数据时定义它们,并从任何中间件访问它们。

¥You can define optional route meta when registering them, accessible from any middleware.

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 对象语法定义路由时,也可以添加路由元信息。