最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Node save error "Can't set headers after they are sent" - Stack Overflow

programmeradmin1浏览0评论

I've seen this problem several times on SO and elsewhere, but still couldn't get my code working. When trying to create a new document in node from a POST request I get the following error:

_http_outgoing.js:346
    throw new Error('Can\'t set headers after they are sent.');
    ^

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:346:11)
    at ServerResponse.header (/Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/express/lib/response.js:718:10)
    at ServerResponse.send (/Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/express/lib/response.js:163:12)
    at ServerResponse.json (/Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/express/lib/response.js:249:15)
    at /Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/controllers/transfersController.js:23:12
    at /Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/mongoose/lib/document.js:1743:19
    at handleError (/Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/hooks-fixed/hooks.js:40:22)
    at _next (/Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/hooks-fixed/hooks.js:46:22)
    at fnWrapper (/Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/hooks-fixed/hooks.js:186:18)
    at /Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/mongoose/lib/schema.js:234:13
    at plete (/Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/mongoose/lib/document.js:1128:7)
    at /Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/mongoose/lib/document.js:1157:20
    at ObjectId.SchemaType.doValidate (/Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/mongoose/lib/schematype.js:654:22)
    at /Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/mongoose/lib/document.js:1153:9
    at doNTCallback0 (node.js:428:9)
    at process._tickCallback (node.js:357:13)
[nodemon] app crashed - waiting for file changes before starting...

My code is below. When I console.log request.body I get [object Object], and when I log JSON.stringify(request.body) I get my object that I want. I've tried playing around with adding a return in transfer.save, as the error is in that, but couldn't get it working. Any help would be much appreciated!

app.js

var express              = require('express');
var app                  = express();
var logger               = require('morgan');
var mongoose             = require('mongoose');
var cookieParser         = require('cookie-parser');
var bodyParser           = require('body-parser');
var multer               = require('multer');
var path                 = require('path');
var ejs                  = require('ejs');
var cors                 = require('cors');
var passport             = require('passport');
var port                 = process.env.PORT || 3000;

mongoose.connect('mongodb://localhost:27017/rsstransfers');

var routes = require('./config/routes');

app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true, parameterLimit: 5000}));
app.use(routes);

//runs server on port 3000
app.listen(3000, function() {
        console.log('server has been started on port %s', port);
});

transferController.js

var Transfer = require('../models/Transfer');

//Get all transfers
function getAll(request, response) {
    Transfer.find(function(error, transfers) {
        if(error) response.json({message: 'couldn\'t find any transfers'});

        response.json({ transfers: transfers });
    }).select('-__v');
}

//Create a new transfer
function createTransfer(request, response) {
    console.log('posting');
    console.log('body: ' + request.body);
    console.log(JSON.stringify(request.body));

    var transfer = new Transfer(request.body);
    debugger;
    transfer.save(function(error) {
        if(error) response.json({ message: 'could not create transfer because ' + error });

        response.json({ transfer: transfer });
    });
}

//Delete
function removeTransfer(request, response) {
  var id = request.params.id;

  Transfer.remove({_id: id}, function(error) {
    if(error) response.json({message: 'Could not delete transfer b/c:' + error});

    response.json({message: 'Transfer successfully deleted'});
  }).select('-__v');
}

module.exports = {
    getAll: getAll,
    createTransfer: createTransfer,
    removeTransfer: removeTransfer
}

I've seen this problem several times on SO and elsewhere, but still couldn't get my code working. When trying to create a new document in node from a POST request I get the following error:

_http_outgoing.js:346
    throw new Error('Can\'t set headers after they are sent.');
    ^

Error: Can't set headers after they are sent.
    at ServerResponse.OutgoingMessage.setHeader (_http_outgoing.js:346:11)
    at ServerResponse.header (/Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/express/lib/response.js:718:10)
    at ServerResponse.send (/Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/express/lib/response.js:163:12)
    at ServerResponse.json (/Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/express/lib/response.js:249:15)
    at /Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/controllers/transfersController.js:23:12
    at /Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/mongoose/lib/document.js:1743:19
    at handleError (/Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/hooks-fixed/hooks.js:40:22)
    at _next (/Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/hooks-fixed/hooks.js:46:22)
    at fnWrapper (/Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/hooks-fixed/hooks.js:186:18)
    at /Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/mongoose/lib/schema.js:234:13
    at plete (/Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/mongoose/lib/document.js:1128:7)
    at /Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/mongoose/lib/document.js:1157:20
    at ObjectId.SchemaType.doValidate (/Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/mongoose/lib/schematype.js:654:22)
    at /Users/joshuaswiss/CGA-Code/Transfers/mean-transfers/api/node_modules/mongoose/lib/document.js:1153:9
    at doNTCallback0 (node.js:428:9)
    at process._tickCallback (node.js:357:13)
[nodemon] app crashed - waiting for file changes before starting...

My code is below. When I console.log request.body I get [object Object], and when I log JSON.stringify(request.body) I get my object that I want. I've tried playing around with adding a return in transfer.save, as the error is in that, but couldn't get it working. Any help would be much appreciated!

app.js

var express              = require('express');
var app                  = express();
var logger               = require('morgan');
var mongoose             = require('mongoose');
var cookieParser         = require('cookie-parser');
var bodyParser           = require('body-parser');
var multer               = require('multer');
var path                 = require('path');
var ejs                  = require('ejs');
var cors                 = require('cors');
var passport             = require('passport');
var port                 = process.env.PORT || 3000;

mongoose.connect('mongodb://localhost:27017/rsstransfers');

var routes = require('./config/routes');

app.use(cors());
app.use(logger('dev'));
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true, parameterLimit: 5000}));
app.use(routes);

//runs server on port 3000
app.listen(3000, function() {
        console.log('server has been started on port %s', port);
});

transferController.js

var Transfer = require('../models/Transfer');

//Get all transfers
function getAll(request, response) {
    Transfer.find(function(error, transfers) {
        if(error) response.json({message: 'couldn\'t find any transfers'});

        response.json({ transfers: transfers });
    }).select('-__v');
}

//Create a new transfer
function createTransfer(request, response) {
    console.log('posting');
    console.log('body: ' + request.body);
    console.log(JSON.stringify(request.body));

    var transfer = new Transfer(request.body);
    debugger;
    transfer.save(function(error) {
        if(error) response.json({ message: 'could not create transfer because ' + error });

        response.json({ transfer: transfer });
    });
}

//Delete
function removeTransfer(request, response) {
  var id = request.params.id;

  Transfer.remove({_id: id}, function(error) {
    if(error) response.json({message: 'Could not delete transfer b/c:' + error});

    response.json({message: 'Transfer successfully deleted'});
  }).select('-__v');
}

module.exports = {
    getAll: getAll,
    createTransfer: createTransfer,
    removeTransfer: removeTransfer
}
Share Improve this question asked Jan 6, 2016 at 16:06 Joshua SwissJoshua Swiss 3051 gold badge6 silver badges18 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 7

You are sending response twice. Add return

//don't forget to return the error, otherwise you send response twice
if (error) return response.json({message: 'Could not delete transfer b/c:' + error});

response.json({message: 'Transfer successfully deleted'});
发布评论

评论列表(0)

  1. 暂无评论