Reputation:
I have a HTML form with a post method, and a post route
app.post('/',
c_emailController.create,
c_bookingController.create
);
When i press submit, i need send a email to me and to the client [emailController], and save the data in my bookings collection [bookingController], but sometimes, when i press the submit, this error appears:
Can't set headers after they are sent
The most strange part is: is not everytime, sometimes happens, sometimes don't. Can you check out my controllers code and see if there is a problem?
I believe this is a problem with the next();.
JS FIDDLE -> http://jsfiddle.net/a6s7npcg/
OBS: The code is working when the error not occurs
Upvotes: 1
Views: 344
Reputation: 12324
I think the problem is that you're calling the next
callback twice by calling the sendEmail
function twice.
To avoid that you can use async
library, with the help of which you will send the emails in parallel and and call next
only after both emails are sent.
var async = require('async');
async.parallel({
alertEmail: function(callback) {
var alertEmailOptions = {
to: "myemail@com",
from: "myemail@com",
subject: "[alert]",
html: "some html",
};
sendgrid.send(alertEmailOptions , callback);
},
confirmEmail: function(callback) {
var confirmationEventOptions = {
to: req.body.email,
from: "[email protected]",
subject: "Reserva - "
html: "SOME HTML",
};
sendgrid.send(confirmationEventOptions, callback);
}
}, function (err, results) {
next();
});
Upvotes: 2