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

旧巷老猫 提交于 2019-12-07 18:18:41

问题


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'
            });
    }]);

回答1:


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.


来源:https://stackoverflow.com/questions/21459697/node-js-http-js691-throw-new-errorcan-t-set-headers-after-they-are-sent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!