中间件

¥Middleware

使用 H3 中间件拦截请求、响应和错误。

¥Intercept request, response and errors using H3 middleware.

我们建议尽可能使用可组合的实用程序。全局中间件会使应用逻辑复杂化,使其更难预测和理解。¥!IMPORTANT We recommend using composable utilities whenever possible. Global middleware can complicate application logic, making it less predictable and harder to understand.

全局中间件在每个请求的路由处理程序之前运行,并充当封装器来拦截请求、响应和错误。

¥Global middleware run on each request before route handler and act as wrappers to intercept request, response and errors.

Read more in Request Lifecycle.

你可以使用 H3.use 将全局中间件注册到 应用实例

¥You can register global middleware to app instance using the H3.use.

示例:注册一个全局中间件来记录每个请求。

¥Example: Register a global middleware that logs every request.

app.use((event) => {
  console.log(event);
});

示例:注册一个全局中间件来匹配某些请求。

¥Example: Register a global middleware that matches certain requests.

app.use(
  "/blog/**",
  (event, next) => {
    console.log("[alert] POST request on /blog paths!");
  },
  {
    method: "POST",
    // match: (event) => event.req.method === "POST",
  },
);

你可以使用 next 参数注册中间件,以拦截下一个中间件和处理程序的返回值。

¥You can register middleware with next argument to intercept return values of next middleware and handler.

app.use(async (event, next) => {
  const rawBody = await next();
  // [intercept response]
  return rawBody;
});

以下示例始终使用 Middleware 1 进行响应。

¥Example below, always responsds with Middleware 1.

app
  .use(() => "Middleware 1")
  .use(() => "Middleware 2")
  .get("/", "Hello");
如果中间件返回的值不是 undefinednext() 的结果,它会立即拦截请求处理并发送响应。¥!IMPORTANT If middleware returns a value other than undefined or the result of next(), it immediately intercepts request handling and sends a response.

添加路由时,你可以注册仅与这些路由一起运行的中间件。

¥When adding routes, you can register middleware that only run with them.

import { basicAuth } from "h3";

app.get(
  "/secret",
  (event) => {
    /* ... */
  },
  {
    middleware: [basicAuth({ password: "test" })],
  },
);

为方便起见,H3 提供了中间件工厂函数 onRequestonResponseonError

¥For convenience, H3 provides middleware factory functions onRequest, onResponse, and onError:

import { onRequest, onResponse, onError } from "h3";

app.use(
  onRequest((event) => {
    console.log(`[${event.req.method}] ${event.url.pathname}`);
  }),
);

app.use(
  onResponse((response, event) => {
    console.log(`[${event.req.method}] ${event.url.pathname} ~>`, body);
  }),
);

app.use(
  onError((error, event) => {
    console.log(
      `[${event.req.method}] ${event.url.pathname} !! ${error.message}`,
    );
  }),
);