Siddharth Siddharth - 5 months ago 18
MySQL Question

NodeJS express Authentication using POST returns Error Cannot Set Headers After they Are Sent

I am trying to build a basic Auth using post

app.post("/api/auth",function(req,resp)
{

var username = req.body.username||req.param('username');
var password = req.body.password||req.param('password');
log("Performing Log Check");
log(username + " "+password);

var sent ={};
sent.status =false;
sent.authenticated = false;

var query = {}
query.sql= "SELECT * FROM voix_auth";
query.timeout= 4000; // 40s
connection.query(query, function (error, rows, fields)
{
if(!error)
{
var i=0;
while(i!=rows.length)
{
if(rows[i].username == username && rows[i].password == password)
{
log(rows);
sent.status = true;
sent.authenticated = true;
sent.token = tokenData;
log(sent);
break;
}
i+=1;
}
resp.send(sent);
} //Error Ends
else
{
log("Error Occured");
}

}); //connection Query
log(sent);
resp.send(sent);
});


The issue here is that I get Cannot set header After They are Sent.
So when I remove
resp.send()
this error is gone.

But if the response I get is always false even though the user is Authenticated.

Please help.

Answer Source

You cant send out multiple responses.

Things to change

  • Change query to something like select ONLY_STUFF_YOU_NEED from table where username & passwords match. Take care of sql injection.

  • Wrap the query in a function that returns back a valid user object ONLY if auth matches. Move it outside the controller. Example + shameless plug - https://github.com/swarajgiri/express-bootstrap/tree/master/core

  • After auth is done, send the response using res.send