Bilash
Bilash

Reputation: 3

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

I am verifying user email using verification link. But I got an error on callback. Why?

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

Upvotes: 0

Views: 164

Answers (1)

Stian
Stian

Reputation: 695

so this error:

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

basically means that you already returned your payload to the client, but you are still trying to make changes or sending it again.

I see (and assume) that the cb( txt, null ) callbacks you are calling are for returning messages to the client?

Well, for example in your first conditional, if EMAIL_IS_VERIFIED is false, you send a callback, and then the ".then()" method triggers. Since the .then() method triggers, you are still doing stuff to your payload, even after you sent the first callback.

Now, I'm not sure that this is what triggers the error, but if my assumption is correct, this is already one place it would fail. I see you have a similar approach further down as well, so just look trough your code for code that might send the payload before you are actually ready.

I'm not 100% confident in promises, but I believe you can make your promise flow work similar to what you already have if you just alter how the promises are resolved - Personally I would use a promise library like 'q' to wrap my promises in, but it's been a while since I worked with this stuff.

alternatively you could how the code is structured to resolve this, but I believe you are better off using promises similar to your code now.

Upvotes: 1

Related Questions