Reputation: 235
So I am learning nodejs and mongodb. I am using expressjs and mongojs for the backend and ejs for the front end of my application. What I want to do is the user will select from the drop down to view a list of classes available and the list of classes will show in a table. For example, if the user selects all, all of the classes in the database will show in the table. I am not sure how can I get the value from the drop down menu and display the data from mongodb in a table form. This is what I have so far and I was getting this error: Error: Can't set headers after they are sent.
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') %>
Upvotes: 2
Views: 2292
Reputation: 2597
You can not call both res.send
and res.render
for the same request.
You can pass context to the render
function in the second argument:
res.render('showclass', doc);
Reference: http://expressjs.com/en/guide/using-template-engines.html
Upvotes: 0
Reputation: 4066
res.send
and res.render
both do same thing, they send back response to users, you can't use both of them, remove res.send(doc)
and pass your data to render
method .
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 });
}
});
}
});
take a look at express docs
Upvotes: 1