[英]How to post data back on webpage in node js
Just started working with Node.js and now i successfuly configured Postgres database. 刚开始使用Node.js,现在我成功配置了Postgres数据库。 I can fetched the records from db and I can also see records cound in console.log.
我可以从db获取记录,也可以在console.log中看到记录信息。 But now i am little bit stuck how to post data back on same page.
但是现在我有点卡住了如何将数据发布回同一页上。
I have page called index with two text fields and one submit button. 我有一个名为index的页面,带有两个文本字段和一个提交按钮。 When i submit my data with username and id, i receive this request in request.post method.
当我使用用户名和ID提交数据时,我会在request.post方法中收到此请求。
router.post('/', function (req, res) {
var username = req.body.username;
var userid = req.body.userid;
// method which take parameters and return records from db
getRecords(userid, username, function (result, found) {
if (found) {
console.log(result.rows.length);
}
});
});
After successful transcation from db, I can see the record count in console. 从db成功转换后,我可以在控制台中看到记录数。 But now how can i post this data into the same page (index.ejs) from where i received this request.
但是现在我该如何将这些数据从收到此请求的地方发布到同一页面(index.ejs)。
I tried to do 我试着做
res.send('/', { title: result.rows.length });
and in ejs file 并在ejs文件中
<p>Count is <%= title %></p>
but i received error that "title" is not defined. 但我收到未定义“标题”的错误。 So how can i display count and how can i display the list of records which i fetched from database.
因此,如何显示计数以及如何显示从数据库中获取的记录列表。
只需编写red.send(result)即可,或者如果您想发送多个响应,则可以red.write(result)并记住在网页中捕获了从nodejs发送的结果
You need to use res.render()
if you want to render a template with some variables. 如果要渲染带有一些变量的模板,则需要使用
res.render()
。 For example: 例如:
// or res.render('index', ...)
res.render('index.ejs', { title: result.rows.length });
This assumes you have your app's views settings set up properly. 假设您已经正确设置了应用程序的视图设置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.