简体   繁体   English

使用 nodejs Express 渲染带有数据的 html

[英]Rendering html with data with nodejs Express

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我是表达框架的新手我只想知道如何使用来自 mongo DB 的一些数据呈现 html 页面我使用下面的代码发送 html 但不确定如何发送一些数据

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 ??如何在html中显示数据? if i have sent an array like this如果我发送了这样的数组

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

how to loop this in html ??如何在 html 中循环这个?

I suggest you to use some template engine, like ejs or jade .我建议你使用一些模板引擎,比如ejsjade This form, you can use res.render and send json information for view.这个表单,你可以使用res.render并发送 json 信息进行查看。 For more details consult the engine docs and res.render doc too.有关更多详细信息,请参阅引擎文档和res.render文档。

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.如果你需要在 node.js express 上渲染一个 html 页面,你需要安装任何一个模板引擎,比如 ejs 或 jade,并设置视图目录。 The code used to install ejs using npm is,使用 npm 安装 ejs 的代码是,

npm install ejs --save

include the following code into your app.js file will resolve your problem.将以下代码包含在您的 app.js 文件中将解决您的问题。

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");
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM