Reputation: 6349
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.send(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?
Upvotes: 49
Views: 54931
Reputation: 6780
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
Upvotes: 78
Reputation: 657
Encode the HTML before sending it. Someone made a Gist for this: https://gist.github.com/mikedeboer/1aa7cd2bbcb8e0abc16a
Upvotes: 0
Reputation: 1
The best way to do this is, assuming you're using callback style, declare var output=""....then go through appending what you need to the output var with +=.... use a template literal (new line doesn't matter ${variables in here}
) if it's a large string... then res.writeHead(200,{Content-Type: text/html); res.end(output)
Upvotes: 0
Reputation: 17334
Just add tags around it
someHTML = "<plaintext>" + someHTML + "</plaintext>";
Just a word of caution that the plaintext is considered obsolete which means browser vendors have no obligation to implement them. However ,it still works on major browsers.
Another way you could do it is
someHTML = someHTML.replace(/</g, '<').replace(/>/g, '>');
Upvotes: -3