【问题标题】:Unhandled rejection Error: Can't set headers after they are sent未处理的拒绝错误:发送后无法设置标头
【发布时间】:2016-11-14 06:48:45
【问题描述】:

我正在使用验证链接验证用户电子邮件。但是我在回调时遇到错误。为什么?

错误:未处理的拒绝错误:发送后无法设置标头。

if (req.body.userId && req.body.verificationCode) {
  db.User.findOne({
    where: {
      ID: req.body.userId
    }
  }).then(function(result) {
    if (!result.EMAIL_IS_VERIFIED) {
      return db.EmailVerify.findOne({
        where: {
          VERIFICATION_CODE: req.body.verificationCode
        }
      });
    } else {
      console.log("This email is already verified")
      cb({
        message: 'This email is already verified'
      }, null);
    }
  }).then(function(result) {
    if (result) {
      var now = Date.now();
      if (Math.round(Math.abs((new Date(now) - new Date(result.CREATED_AT)) / (24 * 60 * 60 * 1000))) < 1)
        return db.User.update({
          EMAIL_IS_VERIFIED: true,
          STATUS: 'active'
        }, {
          where: {
            ID: req.body.userId,
            EMAIL: result.EMAIL
          }
        });
      else {
        console.log("Verification Link is experied")
        cb({
          message: 'Your verification link is expired'
        }, null);
      }
    } else {
      console.log("Sorry, Your verification link is not working.")
      cb({
        message: "Sorry, Your verification link is not working."
      }, null);
    }

  }).then(function() {
    return db.User.findOne({
      where: {
        id: req.body.userId
      }
    });
  }).then(function(theUser) {
    return security.makeToken(theUser);
  }).then(function(token) {
    cb(null, {
      message: messages.user.signUpSuccess,
      token: token
    });
  }).catch(function(err) {
    var em = err.message.indexOf('Validation') >= 0 ? "Your provided email is associated with another account!" : err.message;
    cb({
      message: em,
      code: err.code
    }, null);
  })
} else {
  cb({
    message: messages.user.missingInfoAtVerification
  }, null);
}

【问题讨论】:

    标签: javascript node.js express callback


    【解决方案1】:

    所以这个错误:

    错误:未处理的拒绝错误:发送后无法设置标头。

    基本上意味着您已经将负载返回给客户端,但您仍在尝试进行更改或再次发送。

    我看到(并假设)您调用的 cb( txt, null ) 回调是用于向客户端返回消息?

    好吧,例如在您的第一个条件中,如果 EMAIL_IS_VERIFIED 为 false,您发送回调,然后触发“.then()”方法。由于触发了 .then() 方法,即使在您发送了第一个回调之后,您仍在对您的有效负载进行处理。

    现在,我不确定这是触发错误的原因,但如果我的假设是正确的,这已经是它会失败的一个地方。我看到你也有类似的方法,所以只需在你的代码中查看可能在你真正准备好之前发送有效负载的代码。

    我对 Promise 不是 100% 有信心,但我相信如果你只是改变 Promise 的解决方式,你可以让你的 Promise 流程类似于你已经拥有的流程 - 我个人会使用像 'q' 这样的 Promise 库包装我的承诺,但我已经有一段时间没有使用这些东西了。

    或者,您可以通过代码的结构来解决这个问题,但我相信您现在最好使用与您的代码类似的 Promise。

    【讨论】:

      猜你喜欢
      • 2016-09-02
      • 2023-04-04
      • 2017-09-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-20
      相关资源
      最近更新 更多