Hasan A Yousef
Hasan A Yousef

Reputation: 24988

Returning HTML as respond in deno

With the below simple TypeScript code at Deno runtime:

import { serve } from "https://deno.land/[email protected]/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()

Which is executed by running:

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

is displaying a Hello World at the browser.

Is there a way to display an HTML element instead of text, something like displaying <h1> or <button>

Upvotes: 2

Views: 2354

Answers (2)

Robin
Robin

Reputation: 5427

You can add html inside your string like this

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

If you want multiple html element, you can use template literal / template string like this

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>
`);

Upvotes: 0

laserany
laserany

Reputation: 1451

just add your html inside your string

example

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

Upvotes: 3

Related Questions