Home > front end >  Why is the error showing ` catch((err) => {` is not a function?
Why is the error showing ` catch((err) => {` is not a function?

Time:07-25

I'm trying to authenticate users when registering on my app using Nodejs, express and mongoDB. The user gets registered successfully and added to my database but then I get this error in the console that .catch is not a function. Which is after my user has been successfully registered and password hashed successfully as well.

what is the cause of the error that makes my server to crash?

console error:

.catch((err) => {

TypeError: res.status(...).send(...).catch is not a function

My code:

  bcrypt.hash(req.body.password, 10)
  .then((hashedPassword) => {
    const user = new User({
      email: req.body.email,
      password: hashedPassword,
    });
     user.save().then((result) => {
       res.status(201)
          .send({
           message: "User created successfully",
           result,
         }).catch((err) => { 

       // error is pointing at this line of code
           res.status(500).send({
             message: "Error creating User",
             err,
           });
         });
     });
  }).catch((err) => {
    res.status(500).send({
      message: "Password was not hashed successfully",
      err,
    });
  });
});

CodePudding user response:

You placed/copied the catch to the wrong place, it should be catching the error when creating the user not when you send.

So change:

user.save().then((result) => {
   res.status(201).send({
     message: "User created successfully",
     result,
   }).catch((err) => { 
     // error is pointing at this line of code
     res.status(500).send({
       message: "Error creating User",
       err,
     });
   });
});

to

user.save().then((result) => {
   res.status(201).send({
     message: "User created successfully",
     result,
   })
}).catch((err) => {
   res.status(500).send({
     message: "Error creating User",
     err,
   });
});

CodePudding user response:

A few aolutions

1.

You can try to make the code become clearer such as using a try catch function as the code maybe have some problems.

2.

Re-install express(if the problem didn't solve)

npm install express
  • Related