H3
你可以使用 new H3()
创建一个新的 H3 应用实例:
¥You can create a new H3 app instance using new H3()
:
import { H3 } from "h3";
const app = new H3({
/* optional config */
});
H3
方法
¥H3
Methods
H3.fetch
一个与 fetch 兼容的函数,允许获取应用路由。
¥A fetch-compatible function allowing to fetch app routes.
const response = await app.fetch("/");
console.log(response, await response.text());
H3.on
为特定的 HTTP 方法注册路由处理程序。
¥Register route handler for specific HTTP method.
const app = new H3().on("GET", "/", () => "OK");
H3.[method]
为特定的 HTTP 方法注册路由处理程序(app.on(method, ...)
的快捷方式)。
¥Register route handler for specific HTTP method (shortcut for app.on(method, ...)
).
const app = new H3().get("/", () => "OK");
H3.all
注册所有 HTTP 方法的路由处理程序。
¥Register route handler for all HTTP methods.
const app = new H3().all("/", () => "OK");
H3.use
注册全局 中间件。
¥Register a global middleware.
const app = new H3()
.use((event) => {
console.log(`request: ${event.req.url}`);
})
.all("/", () => "OK");
H3.register
注册一个 H3 插件来扩展应用。
¥Register a H3 plugin to extend app.
H3.handler
一个用于组合多个 H3 应用实例的 H3 事件处理程序。
¥An H3 event handler useful to compose multiple H3 app instances.
示例:嵌套应用。
¥Example: Nested apps.
import { H3, serve, redirect, withBase } from "h3";
const nestedApp = new H3().get("/test", () => "/test (sub app)");
const app = new H3()
.get("/", (event) => redirect(event, "/api/test"))
.all("/api/**", withBase("/api", nestedApp.handler));
serve(app);
H3.mount
在基本 URL 下挂载与 .fetch
兼容的服务器实例,例如 Hono 或 Elysia。
¥Mount a .fetch
compatible server instance like Hono or Elysia under the base URL.
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
参数中的基本前缀将被移除。¥!NOTE
Base prefix will be removed from request.url
passed to the mounted app.H3
选项
¥H3
Options
你可以在初始化应用时传递全局应用配置。
¥You can pass global app configuration when initializing an app.
支持的选项:
¥Supported options:
debug
plugins
:(更多信息请参阅 plugins)
debug
选项,会在错误响应中发送重要内容,例如堆栈跟踪。仅在开发期间启用。¥!IMPORTANT
Enabling debug
option, sends important stuff like stack traces in error responses. Only enable during development.全局钩子
¥Global Hooks
初始化 H3 应用时,你可以注册全局钩子:
¥When initializing an H3 app, you can register global hooks:
onError
onRequest
onResponse
这些钩子会在每次请求时调用,可用于向你的应用添加全局逻辑,例如日志记录、错误处理等。
¥These hooks are called for every request and can be used to add global logic to your app such as logging, error handling, etc.
const app = new H3({
onRequest: (event) => {
console.log("Request:", event.req.url);
},
onResponse: (response, event) => {
console.log("Response:", event.path, response.status);
},
onError: (error, event) => {
console.error(error);
},
});
H3
属性
¥H3
Properties
H3.config
全局 H3 实例配置。
¥Global H3 instance config.