Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

javascript - How to get the hashed password to pass into my database?

I am able to run a test in Postman, but for some reason I am not passing my hashed password into the DB correctly.

const express = require("express");
// const helmet = require("helmet");
const { User } = require("./db/models");
const bcrypt = require("bcryptjs");
var salt = bcrypt.genSaltSync(10);
var hash = bcrypt.hashSync('bacon', 8);

const port = 4000;

const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: true, limit: "50mb" }));

// app.use(helmet());

app.get("/", (req, res) => {
  res.send("Hello World!");
});

Here is where i suspect the issue is. I am passing the name, email, and password in. I am trying to figure out how to get the hash to pass into the DB as the password.

app.post("/register", async (req, res) => {
  const user = await User.create({name:req.body.name, email:req.body.email, password:req.body.password});

  bcrypt.genSalt().then(salt => {
    bcrypt.hash("password", salt).then(hash =>{
      console.log(hash);
    });
  })

  console.log(req.body.name)
  res.json(user);
 
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});
question from:https://stackoverflow.com/questions/65895304/how-to-get-the-hashed-password-to-pass-into-my-database

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Since you are in an async function you can use await to get the values before creating the User object

app.post("/register", async (req, res) => {
  const salt = await bcrypt.genSalt();
  const hashed_password = await bcrypt.hash(req.body.password,salt);
  const user = await User.create({name:req.body.name, email:req.body.email, password:hased_password});
  console.log(req.body.name)
  res.json(user);
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...