返回 HTML 作为 deno 中的响应

Returning HTML as respond in deno

使用下面的简单 TypeScript code at Deno 运行时:

import { serve } from "https://deno.land/std@v0.24.0/http/server.ts"

async function main() {
    const body = new TextEncoder().encode("Hello World\n");
    let port = 8000
    const s = serve({ port: port });
    console.log(`Server had been started at:
    http://localhost:${port}/`);
    for await (const req of s) {
      req.respond({ body });
    }
};

main()

由运行执行:

D:\repos\deno>deno --allow-net main.ts
Compile file:///D:/repos/deno/main.ts
Server had been started at:
    http://localhost:8000/

正在浏览器中显示 Hello World

有没有办法显示 HTML 元素而不是文本,比如显示 <h1><button>

只需将 html 添加到字符串中

例子

const body = new TextEncoder().encode("<h1>Hello World</h1>\n");

您可以像这样在字符串中添加 html

const body = new TextEncoder().encode("<h1>Hello World</h1>");

如果你想要多个 html 元素,你可以像这样使用模板文字/模板字符串

const body = new TextEncoder().encode(`
    <div style="display: flex; justify-content: center; align-items: center;">
        <h1>Ryan Dahl From Future</h1>
        <p>Do you need another js runtime ?</p>
    </div>
`);