Rendering html with data with nodejs Express

坚强是说给别人听的谎言 提交于 2020-08-26 08:29:39

问题


I'm new to express framework i just want know how to render html page with some data from mongo DB i used below code to send html but not sure how to send some data

res.sendFile(path + "feature.html"); this is success as html get renders 

send data like this ??

res.sendFile(path + "feature.html", {data: data});

how to display data in html ?? if i have sent an array like this

res.sendFile(path + "feature.html", {data: []});

how to loop this in html ??


回答1:


I suggest you to use some template engine, like ejs or jade. This form, you can use res.render and send json information for view. For more details consult the engine docs and res.render doc too.




回答2:


If you need to render an html page on node.js express, you need to install any of the template engine like ejs or jade and set the view directory. The code used to install ejs using npm is,

npm install ejs --save

include the following code into your app.js file will resolve your problem.

var bodyParser = require('body-parser');
var express = require('express');
var app = express();

app.use(express.static(__dirname + '/'));
app.use(bodyParser.urlencoded({extend:true}));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'ejs');
app.set('views', __dirname);

app.get('/', function(req, res){
    res.render("index");
});


来源:https://stackoverflow.com/questions/37444090/rendering-html-with-data-with-nodejs-express

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