2015-04-28 30 views
2

这里是我的代码:尽管发送状态码,但为什么会收到“错误:发送后无法设置标题”?

app.post('/register', function(req, res){ 
    var user = new User(req.body); 
    if (req.body.password.length <= 5){ res.status(400).send('error: password must be longer'); } 
    if (req.body.username.length <= 3){ res.status(400).send('error: username must be longer'); } 
    User.findOne({ 
    username: req.body.username 
    }, function(err, userr){ 
     if(err) {res.status(400).send(err); } 
     if (userr){res.status(400).send('error: user already exists'); } 
     user.save(function(err, user){ 
     if (err){ res.status(400).send('couldn\tt save fo sum rezon'); }    
     if (user) { res.send(user); } 
     }); 
    }); 
}); 

这里是我的错误:

home/michael/passport-local-implementation/node_modules/mongoose/node_modules/mpromise/lib/promise.js:108 
    if (this.ended && !this.hasRejectListeners()) throw reason; 
                ^
Error: Can't set headers after they are sent. 

我感到困惑,我要送头不止一次?这些代码不应该在满足其中一个条件时立即停止执行,或者如果没有满足条件,那么只需渲染用户?

奖励积分如果有人可以给我资源在哪里阅读如何快速路由工作的细节点!

+0

与此类似的问题(但不完全相同的副本):https://stackoverflow.com/questions/7042340/node-js-error-cant -set-headers-after-they-are-sent –

回答

2

采取例如以下行:

if (req.body.password.length <= 5){ res.status(400).send('error: password must be longer'); } 

如果条件被满足,表达会发送一个响应,但是该功能不会返回,因此,下一行被评估等等..

您应该简单地添加一个return;以确保函数在发送响应时返回。

下面是奖励积分;)express routing

UPDATE:

,如果你不使用else你应该总是使用return

... 
    var user = new User(req.body); 
    if (req.body.password.length <= 5){ res.status(400).send('error: password must be longer'); } 
    else if (req.body.username.length <= 3){ res.status(400).send('error: username must be longer'); } 
    else { // include the rest of your function code here... } 

这样,其余的代码只在if失效的情况下评估。

+0

非常好,谢谢John。我是否应该始终添加回复? – h3xc0ntr0l

+0

并不总是......只有当你有条件地发送回应时 –

1

添加到john's answer

如果您的例子:

if (req.body.password.length <= 5){ res.status(400).send('error: password must be longer'); } 
    if (req.body.username.length <= 3){ res.status(400).send('error: username must be longer'); } 

如果req.body.password.length小于或等于3。

两个条件都满足,并在第一if明示发送响应,那么它会在满足第二个条件时尝试发送响应。但是响应和它的头文件已经被发送(如错误所述)。


快递发送方法包括以下任务:

  1. 组报头
  2. 组响应身体
  3. 结束响应(res.end)

所以res.send结束的回应,所以你将无法发送回应一旦发送。

你可能宁愿选择发送响应这样

if (req.body.password.length <= 5){ 
    res.status(400).send('error: password must be longer'); 
    } else if (req.body.username.length <= 3){ 
    res.status(400).send('error: username must be longer'); 
    } 
相关问题