节点保存错误"发送后不能设置标头"

时间:2016-01-06 16:06:44

标签: javascript node.js express

我已经在SO和其他地方多次看到过这个问题,但仍然无法使我的代码正常工作。当尝试从POST请求在节点中创建新文档时,我收到以下错误:

_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 complete (/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...

我的代码如下。当我在console.log request.body时,我得到[object Object],当我记录JSON.stringify(request.body)时,我得到了我想要的对象。我已尝试在transfer.save中添加一个返回,因为错误就在于此,但无法使其正常工作。任何帮助将不胜感激!

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
}

1 个答案:

答案 0 :(得分:7)

您要发送两次回复。添加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'});