当我尝试将用户记录插入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;
2条答案
按热度按时间omqzjyyz1#
kx1ctssn2#
我建议您尽可能地简化代码。