所以我正在学习nodejs和mongodb。我使用expressjs和mongojs作为后端应用程序的前端和ejs。我想要做的是用户将从下拉列表中选择以查看可用类的列表,并且类的列表将显示在表中。例如,如果用户选择全部,则数据库中的所有类都将显示在表中。我不确定如何从下拉菜单中获取值,并以表格形式显示来自MongoDB的数据。这是我到目前为止,我得到此错误:错误:发送后无法设置标头。从下拉列表中获取值显示表nodejs
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">Alloption>
<option value="recent">Recentoption>
<option value="opel">Opeloption>
<option value="audi">Audioption>
select>
<tr>
<th>Class Nameth>
<th>Class Timeth>
<th>Durationth>
<th>Instructorth>
<th>Maximum Studentsth>
<th>Brief Descriptionth>
<th>th>
tr>
<tr>
<td>Datatd>
<td>Datatd>
<td>Datatd>
<td>Datatd>
<td>Datatd>
<td>Datatd>
<td><a href="editclass">Edita>/Deletetd>
tr>
<button type="submit" class="btn btn-default">Submitbutton>
table>
form>
<%- include('includes/footer') %>
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 });
}
});
}
});
看看express docs
这家伙很懒,还没有设置简介