Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render HTML string in Node?

Alright, so I have downloaded Express, set the port with process.env.PORT || 8080, and set the app variable var app = express(). Now, what I'm trying to accomplish is instead of rendering HTML through a file, could I do it through a string?

var html = "<!DOCTYPE html>\n<html>\n    <head>\n    </head>\n <body>\n      <h1>Hello World!</h1>\n   </body>\n</html>";
app.get('/',function(req,res){
   res.render(html);
});

Is there a possible way to do this?

like image 254
baranskistad Avatar asked Jul 11 '16 13:07

baranskistad


People also ask

How do I write HTML code in node?

The most basic way you could do what you want is this : var http = require('http'); http. createServer(function (req, res) { var html = buildHtml(req); res. writeHead(200, { 'Content-Type': 'text/html', 'Content-Length': html.

Can we connect HTML with node js?

Using Clean architecture for Node.So far we sent html code directly from the send(0 function in response object. For sending larger code, we definitely require to have a separate file for html code. Response object gives a sendFile() function to return a html file to client.


2 Answers

the res.render method as specified in the doc : Renders a view and sends the rendered HTML string to the client. So you need to use a template engine eg : jade,ejs, handlebars.. but if your purpose is to only output some html you can do it with res.send instead.

like image 94
Akram Saouri Avatar answered Sep 24 '22 19:09

Akram Saouri


Use res.setHeader set HTTP Response Header

  res.setHeader("Content-Type", "text/html")
  res.send(`
  <h1>Mock API</h1>
  `)
like image 24
Gauss Zhou Avatar answered Sep 20 '22 19:09

Gauss Zhou