响应

H3 响应实用工具。

事件流

createEventStream(event, opts?)

Initialize an EventStream instance for creating server sent events

Example:

import { createEventStream, sendEventStream } from "h3";

app.get("/sse", (event) => {
  const eventStream = createEventStream(event);

  // Send a message every second
  const interval = setInterval(async () => {
    await eventStream.push("Hello world");
  }, 1000);

  // cleanup the interval and close the stream when the connection is terminated
  eventStream.onClosed(async () => {
    console.log("closing SSE...");
    clearInterval(interval);
    await eventStream.close();
  });

  return eventStream.send();
});

清理

sanitizeStatusCode(statusCode?, defaultStatusCode)

Make sure the status code is a valid HTTP status code.

sanitizeStatusMessage(statusMessage)

Make sure the status message is safe to use in a response.

Allowed characters: horizontal tabs, spaces or visible ascii characters: https://www.rfc-editor.org/rfc/rfc7230#section-3.1.2

静态资源服务

serveStatic(event, options)

Dynamically serve static assets based on the request path.

更多响应实用工具

html(event, content)

Respond with HTML content.

Example:

app.get("/", (event) => html(event, "<h1>Hello, World!</h1>"));

iterable(_event, iterable)

Iterate a source of chunks and send back each chunk in order. Supports mixing async work together with emitting chunks.

Each chunk must be a string or a buffer.

For generator (yielding) functions, the returned value is treated the same as yielded values.

Example:

return iterable(event, async function* work() {
  // Open document body
  yield "<!DOCTYPE html>\n<html><body><h1>Executing...</h1><ol>\n";
  // Do work ...
  for (let i = 0; i < 1000) {
    await delay(1000);
    // Report progress
    yield `<li>Completed job #`;
    yield i;
    yield `</li>\n`;
  }
  // Close out the report
  return `</ol></body></html>`;
})
async function delay(ms) {
  return new Promise(resolve => setTimeout(resolve, ms));
}

noContent(event, code?)

Respond with an empty payload.

Example:

app.get("/", () => noContent());

redirect(event, location, code)

Send a redirect response to the client.

It adds the location header to the response and sets the status code to 302 by default.

In the body, it sends a simple HTML page with a meta refresh tag to redirect the client in case the headers are ignored.

Example:

app.get("/", (event) => {
  return redirect(event, "https://example.com");
});

Example:

app.get("/", (event) => {
  return redirect(event, "https://example.com", 301); // Permanent redirect
});

writeEarlyHints(event, hints)

Write HTTP/1.1 103 Early Hints to the client.