2016-11-14 55 views
0

我在使用验证链接验证用户电子邮件。但我在回调中遇到错误。为什么?未处理的拒绝错误:发送后无法设置标题

Error : Unhandled rejection Error: Can't set headers after they are sent.

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

回答

1

所以这个错误:

Error : Unhandled rejection Error: Can't set headers after they are sent.

基本上意味着你已经回到你的有效载荷到客户端,但你还在试图进行更改或再次发送。

我看到(并且假设)您所调用的cb(txt,null)回调函数用于将消息返回给客户端?

那么,例如在您的第一个条件中,如果EMAIL_IS_VERIFIED为false,则发送回调,然后触发“.then()”方法。由于.then()方法触发,所以即使在发送第一个回调之后,您仍然在为有效内容做些什么。

现在,我不确定这是什么触发错误,但如果我的假设是正确的,这已经是一个地方它会失败。我看到你还有一种类似的方法,所以只要看看你的代码是否可以在实际准备好之前发送有效载荷的代码。

我对承诺没有百分百的信心,但我相信你可以让你的诺言流程工作类似于你已经有的,如果你只是改变承诺如何解决 - 我个人会使用承诺库,如'q '包装我的承诺,但自从我与这些东西合作已经有一段时间了。

或者你可以如何构建代码来解决这个问题,但我相信你最好使用类似于你的代码的promise。