Reputation: 245
At the end of an app.post function I am trying to redirect users to a different page (always ends up on the "massChangesSubmitted" page). I keep getting the error Error: Can't set headers after they are sent.
when it hits the line return res.redirect('/mass_changes')
. The SQL section of the code works great, the only thing that fails is the redirect.
I cannot for the life of me figure out why this is happening. Everything I can find online says the res.redirect line should work. Please help!
Post code
app.post('/massChangesSubmitted', function(req, res){
res.status(200).end();
massChangesSubmitted(function(err){});
return res.redirect('/mass_changes');
});
massChangesSubmitted code
function massChangesSubmitted(callback) {
var sql = 'UPDATE mass_changes SET submitted=1, submitted_datetime=now() WHERE submitted=0';
var dbh = mysql.createConnection(config.db["DB"])
dbh.query(sql, function(err, rows) {
if(err) {
callback(-1); // call callback with error.
} else {
callback(1); // call callback function without error.
console.log("Existing Mass Changes considered submitted")
};
dbh.end();
});
};
Upvotes: 0
Views: 453
Reputation: 1079
you have closed the connection when you called
res.status(200).end();
res.end() ends the connection so you would need to remove that. And also as mentioned in the comments res.status 200 might not be needed of its a res.redirect.
If you really need to send 200 then you can specify any valid https status code in redirect.
res.redirect(200, '/mass_changes');
Upvotes: 1