Node.js错误:发送后无法设置标题

我知道这个问题已经存在,但我find的解决scheme并不适合我。 我在Node.js中构build一个基本的创build函数。 它首先检查对象是否已经存在,如果不存在,则创build一个。 而且即使在我添加了else if之后,我也得到这个错误else ifreturn到每个条件。 但似乎一切都执行不pipe。 这是我的代码:

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函数中使用一个函数,但不应该同时使用它们,因为它们都是asynchronous的并且同时被调用。

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

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

尝试在if语句中为响应状态和错误/其他消息设置variables。 那么在你的create函数的最后,返回一个由variables填充的响应对象

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