skistaddy
skistaddy

Reputation: 2224

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?

Upvotes: 24

Views: 47771

Answers (3)

Gauss Zhou
Gauss Zhou

Reputation: 111

Use res.setHeader set HTTP Response Header

  res.setHeader("Content-Type", "text/html")
  res.send(`
  <h1>Mock API</h1>
  `)

Upvotes: 11

Herman Van Der Blom
Herman Van Der Blom

Reputation: 802

You could do it with a string but then you should convert the call to a Javascript call so only the part that needs to be replaced is displayed on the web page. The Ajax call gets from the Controller a : res.send("This is a String) back to its client. At the client you could put this result in a elements innerHtml and then you will have some kind of SPA :-)

Upvotes: 0

Akram Saouri
Akram Saouri

Reputation: 1169

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.

Upvotes: 32

Related Questions