Sunday, 19 March 2017

Node throw new Error('Can\'t set headers after they are sent.')

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

        else {
            res.send("Username or Password is wrong");

        }




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");
})



via Yh1234

No comments:

Post a Comment