所以我正在学习nodejs和mongodb。我的应用程序的后端使用的是高速公路和mongojs,前端是ejs。我想要做的是,用户将从下拉列表中选择查看可用的类列表,类列表将显示在表中。例如,如果用户选择全部,数据库中的所有类都将显示在表中。我不确定如何从下拉菜单中获取值,并以表形式显示来自mongodb的数据。这就是我到目前为止得到的错误:错误:无法在发送后设置标头。
admin.js
router.get('/showclass', function(req, res) {
res.render('showclass');
});
router.post('/showclass', function(req, res) {
var selectValue = req.body.table;
if(selectValue == 'all') {
console.log('All is selected');
db.classes.find().forEach(function(err, doc) {
if(err) {
res.send(err);
} else {
res.send(doc);
res.render('showclass');
}
});
}
});ejs
<%- include('includes/header') %>
<%- include('includes/navbar') %>
<form method="post" action="/admin/showclass">
<table class="table table-bordered">
<label>Show Table By:</label>
<select>
<option value="all">All</option>
<option value="recent">Recent</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<tr>
<th>Class Name</th>
<th>Class Time</th>
<th>Duration</th>
<th>Instructor</th>
<th>Maximum Students</th>
<th>Brief Description</th>
<th></th>
</tr>
<tr>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td>Data</td>
<td><a href="editclass">Edit</a>/Delete</td>
</tr>
<button type="submit" class="btn btn-default">Submit</button>
</table>
</form>
<%- include('includes/footer') %>发布于 2017-12-27 17:49:43
res.send和res.render都做同样的事情,它们向用户发送响应,您不能同时使用它们,删除res.send(doc)并将数据传递给render方法。
router.get('/showclass', function(req, res) {
res.render('showclass');
});
router.post('/showclass', function(req, res) {
var selectValue = req.body.table;
if(selectValue == 'all') {
console.log('All is selected');
db.classes.find().forEach(function(err, doc) {
if(err) {
res.send(err);
} else {
res.render('showclass', { doc: doc });
}
});
}
});看看特快文档
发布于 2017-12-27 18:34:55
对于相同的请求,不能同时调用res.send和res.render。
您可以在第二个参数中将上下文传递给render函数:
res.render('showclass', doc);参考资料:http://expressjs.com/en/guide/using-template-engines.html
https://stackoverflow.com/questions/47996251
复制相似问题