在 Node 中渲染 HTML 字符串?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38308600/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Render HTML string in Node?
提问by baranskistad
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?
好的,所以我已经下载了 Express,使用 设置了端口process.env.PORT || 8080
,并设置了 app 变量var app = express()
。现在,我想要完成的是不是通过文件呈现 HTML,我可以通过字符串来完成吗?
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?
有没有可能的方法来做到这一点?
回答by Akram Saouri
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.
res.render
文档中指定的方法:呈现视图并将呈现的 HTML 字符串发送到客户端。因此,您需要使用模板引擎,例如:jade、ejs、handlebars .. 但如果您的目的是仅输出一些 html,您可以res.send
改为使用它。