Home > front end >  TypeError: Cannot read property 'then' of undefined when using JWT token and refresh token
TypeError: Cannot read property 'then' of undefined when using JWT token and refresh token

Time:04-23

Sorry I'm new to backend (nodejs) and I'm trying to build a JWT token and refresh token but I stumbled across an error that I cannot fix when I try to run an endpoint in insomnia.

TypeError: Cannot read property 'then' of undefined

This is the code snippet from the area the error came from in my app.js file

app.post('/users/login', (req, res) => {
   let email = req.body.email;
   let password = req.body.password;

   User.findByCredentials(email, password)
      .then((user) => {
         return user.createSession()
            .then((refreshToken) => {
               return user.generateAccessAuthToken()
               .then((accessToken) => {
                  return { accessToken, refreshToken };
               });
            })
            .then((authTokens) => {
               res
                  .header('x-refresh-token', authTokens.refreshToken)
                  .header('x-access-token', authTokens.accessToken)
                  .send(user);
            })
   }).catch((e) => {
      res.status(400).send(e);
   });
});

And this is the code for the method "findByCredentials" in my user.model.js file

UserSchema.statics.findByCredentials = function(email, password) {
    let User = this;
    User.findOne({ email }).then((user) => {
        if(!user) return Promise.reject();

        return new Promise((resolve, reject) => {
            bcrypt.compare(password, user.password, (err, res) => {
                if (res) resolve(user);
                else {
                    reject();
                }
            })
        })
    });
}

Please help me

CodePudding user response:

Since the error isn't posted, it's hard to pinpoint the error line & cause. But I would suggest using .catch blocks along with the end of every .then chain and get the spot/line of error

Recommendation:
You are creating a callback hell by using nested .then chains what is call back hell.
Try using async/await syntax to achieve the same functionality in a simplified way - Ref.

Regards,
Muhamed

CodePudding user response:

As if you didn't send any code snippet, it is quite clear. But after going through your code it seems after resolving the "user" you are calling two methods createSession and generateAccessAuthToken. And as you also didn't send any code snippet of these methods I'm assuming you are having error from one of the functions.

And a piece of advice:

  • Related