Reputation: 151
I am having the above problem with one of my node calls. To my knowledge this error shows if you res.send gets called more than once. Looking at the code it should only send res once so I am not sure what is wrong here.
It throws the error when I insert
var express = require('express');
var bodyParser = require('body-parser');
var session = require('express-session');
var cors = require('cors');
var massive = require('massive');
var config = require('./config');
var app = express();
app.use(bodyParser.json());
app.use(cors());
var db = massive.connect({connectionString: config.connectionString}, function(err, localdb){
db = localdb;
app.set('db', db);
});
app.post('/api/login', function(req, res, next) {
db.get_users(function(err, users) {
if(err) res.status(500).json(err);
else {
for(var i = 0; i < users.length; i++) {
if(req.body.email == users[i].email && req.body.password == users[i].password) {
console.log("matched");
var currentUser = users[i];
res.send({
msg: 'passed',
user: currentUser
});
}
else { res.send("Username or Password is wrong"); }
}
}
})
})
app.listen(3000, function() {
console.log("I am listening");
});
Upvotes: 0
Views: 32
Reputation: 707148
You are doing res.send()
inside a for
loop. That means you're calling it multiple times. The error you see is caused when you try to send more than one response to the same request. You can't do that.
I don't know exactly what you're trying to accomplish, but you can either accumulate results in the for
loop and send one response after the for
loop or you can break or return out of the for
loop as soon as you send a response. The point is that you can only send one response.
Upvotes: 1