H3
H3 类是服务器的核心。
你可以使用 new H3()
创建一个新的 H3 应用实例:
import { H3 } from "h3";
const app = new H3({
/* 可选配置 */
});
H3
方法
H3.fetch
一个兼容 fetch 的函数,可以用于获取应用路由。
const response = await app.fetch("/");
console.log(response, await response.text());
H3.on
为特定 HTTP 方法注册路由处理函数。
const app = new H3().on("GET", "/", () => "OK");
H3.[method]
为特定 HTTP 方法注册路由处理函数(相当于 app.on(method, ...)
的快捷方式)。
const app = new H3().get("/", () => "OK");
H3.all
为所有 HTTP 方法注册路由处理函数。
const app = new H3().all("/", () => "OK");
H3.use
注册一个全局的 中间件。
const app = new H3()
.use((event) => {
console.log(`请求: ${event.req.url}`);
})
.all("/", () => "OK");
H3.register
注册一个 H3 插件以扩展应用。
H3.handler
一个 H3 的 事件处理器,用于组合多个 H3 应用实例。
示例: 嵌套路由应用。
import { H3, serve, redirect, withBase } from "h3";
const nestedApp = new H3().get("/test", () => "/test(子应用)");
const app = new H3()
.get("/", (event) => redirect(event, "/api/test"))
.all("/api/**", withBase("/api", nestedApp.handler));
serve(app);
H3.mount
在基础 URL 下挂载一个兼容 .fetch
的服务器实例,比如 Hono 或 Elysia。
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!")),
);
传递给挂载应用的
request.url
会去除基础前缀。H3
选项
初始化应用时,可以传入全局应用配置。
支持的选项:
debug
plugins
: (see plugins for more information)
启用
debug
选项会在错误响应中发送重要信息,如堆栈跟踪。仅在开发时启用。全局钩子
初始化 H3 应用时,可以注册全局钩子:
onError
onRequest
onResponse
这些钩子会在每个请求时调用,可用于添加全局逻辑,比如日志记录、错误处理等。
const app = new H3({
onRequest: (event) => {
console.log("请求:", event.req.url);
},
onResponse: (response, event) => {
console.log("响应:", event.path, response.status);
},
onError: (error, event) => {
console.error(error);
},
});
全局钩子仅在主 H3 应用中运行,不包括子应用。如果需要更多灵活性,请使用 中间件。
H3
属性
H3.config
全局 H3 实例配置。