lundi 6 avril 2015

Headers being sent twice due to callback


var mysql = require('mysql');
var express = require("express");
var router = express.Router();

var mysqlPool = mysql.createPool({...});

router.post("/", function(req, res, nxt) {
req.assert('email', 'Valid email required').notEmpty().isEmail();
var errors = req.validationErrors(true);

if (errors) {
mysqlPool.getConnection(function(err, conn) {
if(err) return nxt(err);
conn.query( 'SELECT * FROM guestbook', function( err, result ) {
conn.release();
return res.render("index", {signs: result, errors: errors || {}})
});
});
}

mysqlPool.getConnection(function(err, conn) {
if(err) return nxt(err);
conn.query( 'INSERT INTO guestbook ( name, email, message ) VALUES ( ?, ?, ? )',
[ req.body.name, req.body.email, req.body.message ],
function( err, result ) {
conn.release();
req.flash( 'success_msg', 'Successfully signed guestbook' );
res.redirect( "/" );
});
});
});


Hi there, im new to node.js


Here is the problem im facing, if there is validation error, this code will produce Can't set headers after they are sent


Im fully aware of why this is happening.

This is because of async callback in the mysqlPool.getConnection get registered and then the flow continue straight to the below code right after it


To remedy this, i add return statement



if (errors) {
return mysqlPool.getConnection(function(err, conn) {...});
}

return mysqlPool.getConnection(function(err, conn) {...});


Yes, it indeed solved my problem.

But i feel something wrong with it.

Is there a better approach to solve this kind of problem?


Aucun commentaire:

Enregistrer un commentaire