【问题标题】:Why do I get "Error: Can't set headers after they are sent" despite sending a status code?尽管发送了状态码,为什么我会收到“错误:发送后无法设置标头”?
【发布时间】:2015-07-07 11:53:45
【问题描述】:

这是我的代码:

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.

我对我多次发送标头的位置感到困惑?是否应该在满足其中一个条件后立即停止执行此代码,或者如果不满足任何条件,则只呈现用户?

如果有人可以给我提供有关在哪里阅读有关快速路由工作原理的详细信息的资源,则可以加分!

【问题讨论】:

标签: node.js http express passport.js


【解决方案1】:

以下面一行为例:

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

如果满足条件,express 将发送响应但函数不会返回,因此下一行将被评估等等..

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

这是奖励积分;)express routing

更新:

如果您不使用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都失败的情况下被评估..

【讨论】:

  • 太好了,谢谢约翰。我是否应该始终添加响应返回?
  • 不总是.. 仅当您有条件地发送响应时
【解决方案2】:

添加到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 express 发送响应,然后在满足第二个条件时再次尝试发送响应。但是是响应,因此它的标头已经发送(如错误所述)。


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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 2017-10-17
    • 2022-01-15
    • 2018-06-08
    • 2018-06-29
    • 2013-12-22
    相关资源
    最近更新 更多