Node Js(express JS)未将记录插入MongoDB,生成错误

4dc9hkyq  于 2023-01-04  发布在  Go
关注(0)|答案(2)|浏览(131)

当我尝试将用户记录插入MongoDB数据库时, Postman 显示了一个错误(500内部服务器错误):“密码未成功散列”。
对于后端,我使用Express JS。我与MongoDB的连接字符串是:
数据库URL=蒙古数据库+服务器:NSreactauth:NSreactauth@happyvivahcluster.pnav1pm.mongodb.net/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;
omqzjyyz

omqzjyyz1#

async function hashPassword(password) {
  const salt = await bcrypt.genSalt(10)
  const hashedPassword = await bcrypt.hash(String(password), salt)
  return hashedPassword
}

app.post("/register", async(request, response) => {
// hash the password
const hashedPassword = await hashPassword(req.body.password);
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,
      });
    });
  });
kx1ctssn

kx1ctssn2#

我建议您尽可能地简化代码。

app.post("/register", async (request, response) => {
    try {
        let hashedPassword = await bcrypt.hash(request.body.password, 10) // create has password

        const user = new User({
            email: request.body.email,
            password: hashedPassword,
        }); //prepare user data
        await user.save() //save user data
        response.status(201).send({
            message: "User Created Successfully",
            user,
        }); //send success response
    } catch (e) {
        response.status(500).send({
            message: e.message,
            error,
        }); //send error response
    }
})

相关问题