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,
});
});
});
2
Answers
A few aolutions
1.Check your catch() function
You can try to make the code become clearer such as using a try catch function as the code maybe have some problems.
2. If problem #1 didn’t work
Re-install express(if the problem didn’t solve)
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:
to