# H3
> H3 类是服务器的核心。
你可以使用 `new H3()` 创建一个新的 H3 应用实例:
```js
import { H3 } from "h3";
const app = new H3({
/* 可选配置 */
});
```
## `H3` 方法
### `H3.request`
一个兼容 [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) 的函数,可以用于获取应用路由。
- 输入可以是相对路径、[URL](https://developer.mozilla.org/en-US/docs/Web/API/URL),或 [Request](https://developer.mozilla.org/en-US/docs/Web/API/Request)。
- 返回值是一个 [Response](https://developer.mozilla.org/en-US/docs/Web/API/Response) 的 Promise。
```ts
const response = await app.request("/");
console.log(response, await response.text());
```
### `H3.fetch`
类似于 `H3.request`,但仅接受一个 `(req: Request)` 参数以实现跨运行时兼容性。
### `H3.on`
为特定 HTTP 方法注册路由处理函数。
```js
const app = new H3().on("GET", "/", () => "OK");
```
### `H3.[method]`
为特定 HTTP 方法注册路由处理函数(相当于 `app.on(method, ...)` 的快捷方式)。
```js
const app = new H3().get("/", () => "OK");
```
### `H3.all`
为所有 HTTP 方法注册路由处理函数。
```js
const app = new H3().all("/", () => "OK");
```
### `H3.use`
注册一个全局的 [中间件](/guide/basics/middleware)。
```js
const app = new H3()
.use((event) => {
console.log(`请求: ${event.req.url}`);
})
.all("/", () => "OK");
```
### `H3.register`
注册一个 H3 插件以扩展应用。
### `H3.handler`
一个 H3 的 [事件处理器](/guide/basics/handler),用于组合多个 H3 应用实例。
**示例:** 嵌套路由应用。
```js
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`
使用 `.mount` 方法,您可以注册带有前缀的子应用。
## `H3` 选项
初始化应用时,可以传入全局应用配置。
支持的选项:
- `debug`: Displays debugging stack traces in HTTP responses (potentially dangerous for production!).
- `silent`: When enabled, console errors for unhandled exceptions will not be displayed.
- `plugins`: (see [plugins](/guide/advanced/plugins) for more information)
启用 `debug` 选项会在错误响应中发送重要信息,如堆栈跟踪。仅在开发时启用。
### 全局钩子
初始化 H3 应用时,可以注册全局钩子:
- `onError`
- `onRequest`
- `onResponse`
这些钩子会在每个请求时调用,可用于添加全局逻辑,比如日志记录、错误处理等。
```js
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 应用中运行,**不**包括子应用。如果需要更多灵活性,请使用 [中间件](/guide/basics/middleware)。
## `H3` 属性
### `H3.config`
全局 H3 实例配置。