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.request
一个与 fetch 兼容的函数,允许获取应用路由。
¥A fetch-compatible function allowing to fetch app routes.
const response = await app.request("/");
console.log(response, await response.text());
H3.fetch
与 H3.request
类似,但为了跨运行时兼容性,它只接受一个 (req: Request)
参数。
¥Similar to H3.request
but only accepts one (req: Request)
argument for cross runtime compatibility.
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
使用 .mount
方法,你可以注册一个带前缀的子应用。
¥Using .mount
method, you can register a sub-app with prefix.
H3
选项
¥H3
Options
你可以在初始化应用时传递全局应用配置。
¥You can pass global app configuration when initializing an app.
支持的选项:
¥Supported options:
debug
:在 HTTP 响应中显示调试堆栈跟踪(对生产环境可能存在危险!)。silent
:启用后,未处理异常的控制台错误将不会显示。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.