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?
Delivering HTML files using Express can be useful when you need a solution for serving static pages.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With