Utils
响应
发送响应头和数据的工具
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:
noContent(event, code?)
Respond with an empty payload.
Example:
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:
writeEarlyHints(event, hints)
Write HTTP/1.1 103 Early Hints
to the client.
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));
}
app.use("/", () => noContent());
app.use("/", (event) => {
return redirect(event, "https://example.com");
});
Example:
app.use("/", (event) => {
return redirect(event, "https://example.com", 301); // Permanent redirect
});