gpt4 book ai didi

javascript - Node.js错误: Can't set headers after they are sent

转载 作者:太空宇宙 更新时间:2023-11-04 00:30:09 25 4
gpt4 key购买 nike

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

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

最佳答案

您应该在 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')});
});
}
});
},
}

关于javascript - Node.js错误: Can't set headers after they are sent,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41244612/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com