Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Render raw html in response with Express

I would like to know how to render a raw HTML string in a response with Express.

My question is different from the others because I am not trying to render a raw HTML template; rather I just want to render a single raw HTML string.

Here is what I have tried in my route file.

router.get('/myRoute', function (req, res, next) {   var someHTML = "<a href=\"foo\">bar</a>"   res.end(someHTML); }); 

But when I point my browser to this route, I see a hyperlink, instead of a raw HTML string. I have tried to set the content-type to text by doing: res.setHeader('Content-Type', 'text'); with no avail.

Any suggestions?

like image 777
Sung Cho Avatar asked Sep 16 '15 06:09

Sung Cho


People also ask

Can Express serve HTML?

Delivering HTML files using Express can be useful when you need a solution for serving static pages.

How do I open an HTML file on Express server?

For a file path, the server tries to find the path of the file from the root directory, so it gets mandatory to specify either the entire path or use the '_dirname', else always the file not found error will be faced. var express = require("express"); var path = require('path'); var app = express(); app.


1 Answers

For others arriving here; this worked best for me:

res.set('Content-Type', 'text/html'); res.send(Buffer.from('<h2>Test String</h2>')); 

Edit:

And if your issue is escaping certain characters, then try using template literals: Template literals

like image 61
Richard Dunn Avatar answered Oct 06 '22 06:10

Richard Dunn