Render raw html in response with Express

时光怂恿深爱的人放手 提交于 2020-01-22 17:55:06

问题


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?


回答1:


For others arriving here; this worked best for me:

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

Edit:

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




回答2:


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, '&lt;').replace(/>/g, '&gt;');



回答3:


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)

|improve this answer

来源:https://stackoverflow.com/questions/32601424/render-raw-html-in-response-with-express

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!