Leonardo Leonardo - 3 years ago 152
Node.js Question

express - Error: Can't set headers after they are sent

Hello I tried everything but the following very simple code gives me the "Can't set headers after they are sent" error, I've been working on this for days you're input is highly appreciated.

app.post('/login', function (req, res) {
var emailpassed = req.body.email

var shaObj = new jsSHA('SHA-256', 'TEXT')
shaObj.update('zzzz' + req.body.password)
var hash = shaObj.getHash('HEX')

var params = {
TableName: 'passengers',
IndexName: 'emailpass',
ProjectionExpression: 'password',
KeyConditionExpression: '#yr = :yyyy',
ExpressionAttributeNames: {
'#yr': 'email'
},
ExpressionAttributeValues: {
':yyyy': emailpassed
}
}

docClient.query(params, function (err, data) {
if (err) {
console.log('No such user found.1')

} else {
data.Items.forEach(function (item) {
if (item.password != hash) {
console.log('Incorrect password.1')
} else {

var payload = {id: item.pid, password: hash}
var token = jwt.sign(payload, 'sa')

if (token) {
return res.json({token: token})

}
}

})
console.log('daaakey')

}
})
return;
}
)

Answer Source

You are calling res.json() inside a .forEach() loop which means you can call it more than once any time data.Items.length is more than 1 and some other conditions are met. Remember that when you do return res.json(), the return is returning from the .forEach() callback and thus the .forEach() loop continues to run and the callback an be called again. The error you are seeing is caused by attempting to send more than one response to a given request which is not permitted.

You need to restructure your code flow such that your either your .forEach() loop gathers input (often in an array) and then sends one response containing all the data after the loop is done or if you only intend to send a response on the first token found, then you probably want to switch to a regular for loop so you can break out of the loop after you send the response (to avoid sending another one) with a return or break. It is not clear from your code which of these scenarios is your likely intention (sending only the first data or accumulating all the data and sending it all).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download