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

Hello I am making simple application using MEAN stack. And I get this error http.js:691 throw new Error('Can\'t set headers after they are sent.')

Here is the code: server.js

// set up
var express = require('express');
var app = express();
var mongoose = require('mongoose');

// mongodb connection and app configuration
mongoose.connect('mongodb://localhost/test');

app.configure(function () {
    app.use(express.static(__dirname + '/app'));
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());
});

// define model
var Employee = mongoose.model('Employee', {
    firstName : String,
    lastName : String,
    photoUrl : String
});

// routes ==========================
// api
// GET
app.get('/api/employees', function(req, res) {
    console.log("GET");
    Employee.find(function(err, employees) {
        if(err) {
            res.send(err);
        }

        res.json(employees);
    });
});

// Get by ID
app.get('/api/employees/:employeeId', function(req, res) {
    Employee.findById(req.params.employeeId, function(err, employee) {
        if(err) {
            res.send(err);
        }

        res.json(employee);
    });
    Employee.find(function(err, employees) {
        if(err) {
            res.send(err);
        }

        res.json(employees);
    });
});

// POST
app.post('/api/employees', function(req, res) {
    Employee.create({
        firstName : req.body.firstName,
        lastName : req.body.lastName,
        photoUrl : req.body.photoUrl
    }, function(err, employee) {
        if(err) {
            res.send(err);
        }
        Employee.find(function(err, employees){
            if(err) {
                res.send(err);
            }
            res.json(employees);
        });
    });
});

// DELETE
app.delete('/api/employees/:employee_id', function(req, res) {
    Employee.remove({_id : req.params.employee_id}, function (err, employee) {
        if(err) {
            res.send(err);
        }

        Employee.find(function(err, employees) {
            if(err) {
                res.send(err);
            }
            res.json(employees);
        })
    });
});

// application
app.get('*', function(req, res) {
    res.sendfile('./app/index.html'); 
});

// start listening (start app)
app.listen(8080);
console.log("App listening on port 8080");

And also: app.js Angular routes

var employeesApp = angular.module('employeesApp', [
    'ngRoute',
    'EmployeesControllers',
    'employeeAppAnimations'
]);

employeesApp.config(['$routeProvider',
    function($routeProvider) {
        $routeProvider.
            when('/employees', {
                templateUrl: 'partials/employees_list.html',
                controller: 'EmployeesCtrl'
            }).
            when('/employees/:employeeId', {
                templateUrl: 'partials/employees_details.html',
                controller: 'EmployeeDetailsCtrl'
            }).
            otherwise({
                redirectTo: '/employees'
            });
    }]);

Answers


In

app.get('/api/employees/:employeeId', function() {...});

you are using res.json twice. Lets assume Employee.findById returns the results first. Then,

res.json(employee)

is already sent. Then the code enters Employee.find callback with a slight delay. This again triggers res.json(). But since the response to your request is already sent, it can't send another response to the same request.

This condition is throwing the error.

There are two ways to solve this.

  1. Nested callbacks - Call Employee.find inside Employee.findById callback.
  2. Add conditions in both the callbacks to check if other callback is complete. Then send a single response.

Need Your Help

Using OR along with join query results causing NullPointerException

solr lucene solr4 solrcloud

Following are the sample documents and fields configured in my solr 4.7.2

Modify filepath to use in Printf

c++ c windows printf

I have a string which is something like "c:\x\y\z"