When I am trying to insert the user’s record into the MongoDB database it shows an error (500 Internal Server Error) on the postman with "message": "Password was not hashed successfully".
For the backend, I am using Express JS.
And my Connection String with MongoDB is :
DB_URL=mongodb+srv://NSreactauth:[email protected]/reactauthapp?retryWrites=true&w=majority
const express = require("express");
const app = express();
const bodyParser = require("body-parser");
const bcrypt = require("bcrypt");
const jwt = require("jsonwebtoken");
// require database connection
const dbConnect = require("./db/dbConnect");
const User = require("./db/userModel");
const auth = require("./auth");
// execute database connection
dbConnect();
// Curb Cores Error by adding a header here
app.use((req, res, next) => {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader(
"Access-Control-Allow-Headers",
"Origin, X-Requested-With, Content, Accept, Content-Type, Authorization"
);
res.setHeader(
"Access-Control-Allow-Methods",
"GET, POST, PUT, DELETE, PATCH, OPTIONS"
);
next();
});
// body parser configuration
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.get("/", (request, response, next) => {
response.json({ message: "Hey! This is your server response!" });
next();
});
// register endpoint
app.post("/register", (request, response) => {
// hash the password
bcrypt.hash(request.body.password, 10)
.then((hashedPassword) => {
// create a new user instance and collect the data
const user = new User({
email: request.body.email,
password: hashedPassword,
});
// save the new user // return success if the new user is added to the database successfully
user.save().then((result) => {
response.status(201).send({
message: "User Created Successfully",
result,
});
})
// catch erroe if the new user wasn't added successfully to the database
.catch((error) => {
response.status(500).send({
message: "Error creating user",
error,
});
});
})
// catch error if the password hash isn't successful
.catch((e) => {
response.status(500).send({
message: "Password was not hashed successfully",
e,
});
});
});
module.exports = app;
2
Answers
I would suggest making your code as simple as you can.