【问题标题】:Node.js Error: Can't set headers after they are sentNode.js 错误:发送后无法设置标头
【发布时间】:2016-12-21 00:15:56
【问题描述】:

我知道这个问题已经存在,但我找到的解决方案对我不起作用。我正在 Node.js 中构建一个基本的创建函数。它首先检查对象是否已经存在,如果不存在,则创建一个。即使在每个条件中添加了 else ifreturn 后,我也会收到此错误。但似乎一切都被执行了。这是我的代码:

controllers/shop.js:

var Shop = require('../models/shop').model;
module.exports = {
    create: function(req, res) {
        if(typeof(req) != 'object')
            return res.status(400).send({error: Error.InvalidInput});
        if(req.body.name === null) return res.status(400).json({error: Error.missingParameter('name')});
        Shop.findOne({name: req.body.name}, function(err, shop){
            if(err) return res.status(500).json({error: Error.unknownError});
            else if (shop) return res.status(409).json({error: Error.alreadyExists('Shop')});
        }).exec(Shop.create({name: req.body.name}, function(err, shop) {
            if (err) return res.status(500).json({error: Error.unknownError});
            else if (shop) return res.status(201).json(shop);
            else if (!shop) return res.status(400).json({error: Error.createFailed('Shop')});
        }));
    },
}

【问题讨论】:

  • 你得到的回应是什么?
  • @Sam 错误:发送后无法设置标头。

标签: javascript node.js mongodb mongoose


【解决方案1】:

您应该在find 方法中传递callback,或者使用带有exec 的函数,但不应同时使用两者,因为它们都是异步的并且同时被调用。

你可以重构你的代码如下。

var Shop = require('../models/shop').model;
module.exports = {
    create: function(req, res) {
        if(typeof(req) != 'object')
            return res.status(400).send({error: Error.InvalidInput});
        if(req.body.name === null) return res.status(400).json({error: Error.missingParameter('name')});
        Shop.findOne({name: req.body.name}, function(err, shop){
            if(err) return res.status(500).json({error: Error.unknownError});
            else if (shop) return res.status(409).json({error: Error.alreadyExists('Shop')});
            else {
                Shop.create({name: req.body.name}, function(err, shop) {
                if (err) return res.status(500).json({error: Error.unknownError});
                else if (shop) return res.status(201).json(shop);
                else if (!shop) return res.status(400).json({error: Error.createFailed('Shop')});
        });
            }
        });
    },
}

【讨论】:

  • 这行得通!但是在我接受之前你能把find() 改成findOne() 吗?因为find 总是返回一个数组,使得第二个条件else if (shop) 始终为真,即使数组为空。再次感谢! :)
【解决方案2】:

尝试在 if 语句中为响应状态和错误/其他消息设置变量。然后在你的 create 函数结束时返回一个填充了变量的响应对象

var Shop = require('../models/shop').model;
module.exports = {
    create: function(req, res) {
        var status = 200;
        var message = "";
        if(typeof(req) != 'object')
            status = 400;
            message = Error.InvalidInput;
           ...
        return res.status(status).send({error: message});
          });
        }));
    },
}

【讨论】:

    猜你喜欢
    • 2019-04-22
    • 2012-07-25
    • 2015-05-21
    • 2015-09-08
    • 1970-01-01
    • 1970-01-01
    • 2011-10-17
    • 2018-03-13
    • 1970-01-01
    相关资源
    最近更新 更多