发送响应

¥Sending Response

H3 自动将任何返回值转换为 Web 响应。

¥H3 automatically converts any returned value into a web response.

H3 会自动将 事件处理程序 返回的值转换为 Web 响应

¥Values returned from Event Handlers are automatically converted to a web Response by H3.

示例:简单的事件处理函数。

¥Example: Simple event handler function.

const handler = defineHandler((event) => ({ hello: "world" }));

H3 智能地将处理程序转换为:

¥H3 smartly converts handler into:

const handler = (event) =>
  new Response(JSON.stringify({ hello: "world" }), {
    headers: {
      "content-type": "application/json;charset=UTF-8",
    },
  });
🚀 H3 内部使用 srvx FastResponse 来优化 Node.js 运行时的性能。¥!TIP 🚀 H3 uses srvx FastResponse internally to optimize performances in Node.js runtime.

如果事件处理程序的返回值是 Promise异步函数,H3 将等待其解析后再发送响应。

¥If the returned value from event handler is a Promise or from an async function, H3 will wait for it to resolve before sending the response.

如果抛出错误,H3 会自动使用错误处理程序进行处理。

¥If an error is thrown, H3 automatically handles it with error handler.

Read more in Error Handling.

准备响应

¥Preparing Response

在主处理程序中返回响应之前,你可以使用 event.res 准备响应头和状态。

¥Before returning a response in main handler, you can prepare response headers and status using event.res.

defineHandler((event) => {
  event.res.status = 200;
  event.res.statusText = "OK";
  event.res.headers.set("Content-Type", "text/html");
  return "<h1>Hello, World</h1>";
});
如果返回完整的 响应 值,则已准备好的状态将被丢弃,并且标头将被合并/覆盖。出于性能原因,在这种情况下,最好仅从最终的 Response 中设置标头。¥!NOTE If a full Response value is returned, prepared status is discarded and headers will be merged/overriden. For performance reasons, it is best to only set headers only from final Response in this case.
如果发生错误,已准备好的状态和标头将被丢弃。¥!NOTE If an Error happens, prepared status and headers will be discarded.

响应类型

¥Response Types

H3 智能地将 JavaScript 值转换为 Web 响应

¥H3 smartly converts JavaScript values into web Response.

JSON 可序列化值

¥JSON Serializable Value

返回 JSON 可序列化值(对象、数组、数字或布尔值)时,它将使用 JSON.stringiy() 进行字符串化,并以默认的 application/json 内容类型发送。

¥Returning a JSON serializable value (object, array, number or boolean), it will be stringified using JSON.stringiy() and sent with default application/json content-type.

示例:

¥Example:

app.get("/", (event) => ({ hello: "world" }));
返回的具有 .toJSON() 属性的对象可以自定义序列化行为。查看 MDN 文档 了解更多信息。¥!TIP Returned objects with .toJSON() property can customize serialization behavior. Check MDN docs for more info.

字符串

¥String

返回字符串值时,将其作为纯文本正文发送。

¥Returning a string value, sends it as plain text body.

如果未设置 content-type 标头,则可以默认使用 text/plain;charset=UTF-8。¥!NOTE If not setting content-type header, it can default to text/plain;charset=UTF-8.

示例:发送 HTML 响应。

¥Example: Send HTML response.

app.get("/", (event) => {
  event.res.headers.set("Content-Type", "text/html;charset=UTF-8");
  return "<h1>hello world</h1>";
});

你也可以使用 html 实用程序作为快捷方式。

¥You can also use html utility as shortcut.

import { html } from "h3";

app.get("/", (event) => html(event, "<h1>hello world</h1>"));

Response

返回 Web 响应 时,将其作为最终响应发送。

¥Returning a web Response, sends-it as final reponse.

示例:

¥Example:

app.get(
  "/",
  (event) =>
    new Response("Hello, world!", { headers: { "x-powered-by": "H3" } }),
);
发送 Response 时,之前设置的任何 准备好的标头 都将合并为默认标头。event.res.{status,statusText} 将被忽略。出于性能原因,最好仅从最终的 Response 中设置标头。¥!IMPORTANT When sending a Response, any prepared headers that set before, will be merged as default headers. event.res.{status,statusText} will be ignored. For performance reasons, it is best to only set headers only from final Response.

ReadableStreamReadable

¥ReadableStream or Readable

返回 ReadableStream 或 Node.js Readable 会将其作为流发送。

¥Returning a ReadableStream or Node.js Readable sends it as stream.

ArrayBufferUint8ArrayBuffer

¥ArrayBuffer or Uint8Array or Buffer

发送二进制 ArrayBufferUint8Array 或 Node Buffer

¥Send binary ArrayBuffer, Uint8Array or node Buffer.

content-length 标头将自动设置。

¥content-length header will be automatically set.

Blob

以流形式发送 Blob

¥Send a Blob as stream.

Content-typeContent-Length 标头将自动设置。

¥Content-type and Content-Length headers will be automatically set.

File

以流形式发送 File

¥Send a File as stream.

Content-typeContent-LengthContent-Disposition 标头将自动设置。

¥Content-type, Content-Length and Content-Disposition headers will be automatically set.

特殊类型

¥Special Types

一些不太常见的响应类型值。

¥Some less commonly possible values for response types.

nullundefined

¥null or undefined

发送包含空正文的响应。

¥Sends a response with empty body.

如果事件处理程序中没有 return 语句,则其与 return undefined 相同。¥!TIP If there is no return statement in event handler, it is same as return undefined.

Error

重新调整 Error 实例将发送它。

¥Retuning an Error instance will send it.

最好是 throw 错误,而不是直接返回错误。这允许从任何嵌套实用程序进行正确传播。¥!IMPORTANT It is better to throw errors instead of returning them. This allows proper propagation from any nested utility.
Read more in Error Handling.

BigInt

值将以 BigInt 数值的字符串形式发送。

¥Value will be sent as stringified version of BigInt number.

返回 JSON 对象,不允许 BigInt 序列化。你需要实现 .toJSON。查看 MDN 文档 了解更多信息。¥!NOTE Returning a JSON object, does not allows BigInt serialization. You need to implement .toJSON. Check MDN docs for more info.

SymbolFunction

¥Symbol or Function

返回符号或函数具有不确定的行为。目前,H3 会发送未知符号和函数的字符串表示形式,但此行为可能会在未来版本中更改为抛出错误。

¥Returning Symbol or Function has undetermined behavior. Currently, H3 sends a string-like representation of unknown Symbols and Functions but this behavior might be changed to throw an error in the future versions.

H3 内部使用了一些已知的内部符号:

¥There are some internal known Symbols H3 internally uses:

  • Symbol.for("h3.notFound"):表示未找到路由,则抛出 404 错误。
  • Symbol.for("h3.handled"):表示请求已得到某种处理,H3 不应继续(Node.js 专用)。