H3Event
对于每个 HTTP 请求,H3 都会在内部创建一个 H3Event
对象,并将其传递给事件处理程序,直到发送响应。
¥With each HTTP request, H3 internally creates an H3Event
object and passes it though event handlers until sending the response.
事件会传递到所有生命周期钩子和可组合实用程序,并将其用作上下文。
¥An event is passed through all the lifecycle hooks and composable utils to use it as context.
示例:
¥Example:
app.get("/", async (event) => {
// Log HTTP request
console.log(`[${event.req.method}] ${event.req.url}`);
// Parsed URL and query params
const searchParams = event.url.searchParams;
// Try to read request JSON body
const jsonBody = await event.req.json().catch(() => {});
return "OK";
});
H3Event
方法
¥H3Event
Methods
H3Event.waitUntil
告知运行时正在进行的操作,该操作在 Promise 解析完成之前不应关闭。
¥Tell the runtime about an ongoing operation that shouldn't close until the promise resolves.
import { logRequest } from "./tracing.mjs";
app.get("/", (event) => {
request.waitUntil(logRequest(request));
return "OK";
});
export async function logRequest(request) {
await fetch("https://telemetry.example.com", {
method: "POST",
body: JSON.stringify({
method: request.method,
url: request.url,
ip: request.ip,
}),
});
}
H3Event
属性
¥H3Event
Properties
H3Event.context
上下文是一个包含任意请求信息的对象。
¥The context is an object that contains arbitrary information about the request.
你可以将自定义属性存储在 event.context
中,以便在实用程序之间共享。
¥You can store your custom properties inside event.context
to share across utils.
已知上下文键:
¥Known context keys:
context.params
:匹配的路由参数。middlewareParams
:匹配的中间件参数matchedRoute
:匹配的路由路由对象。sessions
:缓存会话数据。basicAuth
:基本身份验证数据。
H3Event.req
基于原生 Web 请求 和附加运行时插件(参见 srvx 文档)的传入 HTTP 请求信息。
¥Incoming HTTP request info based on native Web Request with additional runtime addons (see srvx docs).
app.get("/", async (event) => {
const url = event.req.url;
const method = event.req.method;
const headers = event.req.headers;
// (note: you can consume body only once with either of this)
const bodyStream = await event.req.body;
const textBody = await event.req.text();
const jsonBody = await event.req.json();
const formDataBody = await event.req.formData();
return "OK";
});
H3Event.url
访问已解析的完整请求 URL。
¥Access to the full parsed request URL.
H3Event.res
准备好 HTTP 响应状态和标头。
¥Prepared HTTP response status and headers.
app.get("/", (event) => {
event.res.status = 200;
event.res.statusText = "OK";
event.res.headers.set("x-test", "works");
return "OK";
});