嵌套应用
¥Nested Apps
H3 拥有原生的
mount
方法,用于将嵌套的子应用添加到主实例。¥H3 has a native
mount
method for adding nested sub-apps to the main instance.
通常,H3 项目由在一个或多个文件中定义的多个 事件处理程序 组成(为了加快启动速度,甚至可以使用 延迟加载)。
¥Typically, H3 projects consist of several Event Handlers defined in one or multiple files (or even lazy loaded for faster startup times).
有时,组合多个 H3
实例甚至使用其他团队使用的 HTTP 框架并将其挂载到主应用实例会更方便。H3 提供了原生的 .mount
方法来实现这一点。
¥It is sometimes more convenient to combine multiple H3
instances or even use another HTTP framework used by a different team and mount it to the main app instance. H3 provides a native .mount
method to facilitate this.
嵌套 H3 应用
¥Nested H3 Apps
H3 原生支持挂载子应用。挂载后,子应用的路由和中间件将与基本 URL 前缀合并到主应用实例中。
¥H3 natively allows mounting sub-apps. When mounted, sub-app routes and middleware are merged with the base url prefix into the main app instance.
import { H3, serve } from "h3";
const nestedApp = new H3()
.use((event) => {
event.res.headers.set("x-api", "1");
})
.get("/**:slug", (event) => ({
pathname: event.url.pathname,
slug: event.context.params?.slug,
}));
const app = new H3().mount("/api", nestedApp);
在上面的例子中,获取 /api/test
URL 时,pathname
将是 /api/test
(真实路径),slug
将是 /test
(通配符参数)。
¥In the example above, when fetching the /api/test
URL, pathname
will be /api/test
(the real path), and slug
will be /test
(wildcard param).
嵌套 Web 标准应用
¥Nested Web Standard Apps
在基本 URL 下挂载与 .fetch
兼容的服务器实例,例如 Hono 或 Elysia。
¥Mount a .fetch
compatible server instance like Hono or Elysia under the base URL.
request.url
参数中的基本前缀将被移除。¥!NOTE
Base prefix will be removed from request.url
passed to the mounted app.import { H3 } from "h3";
import { Hono } from "hono";
import { Elysia } from "elysia";
const app = new H3()
.mount(
"/elysia",
new Elysia().get("/test", () => "Hello Elysia!"),
)
.mount(
"/hono",
new Hono().get("/test", (c) => c.text("Hello Hono!")),
);