【问题标题】:Returning HTML as respond in deno在 deno 中返回 HTML 作为响应
【发布时间】:2020-05-15 02:19:43
【问题描述】:

Deno 运行时使用以下简单的TypeScript 代码:

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>

【问题讨论】:

    标签: deno


    【解决方案1】:

    只需在字符串中添加 html

    例子

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

    【讨论】:

    【解决方案2】:

    您可以像这样在字符串中添加 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>
    `);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-02
      • 2023-03-28
      • 1970-01-01
      • 2013-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多