Howie
Howie

Reputation: 145

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}`);
});

Upvotes: 0

Views: 448

Answers (2)

Girish Srivatsa
Girish Srivatsa

Reputation: 323

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);
});

Upvotes: 2

王仁宏
王仁宏

Reputation: 396

const hashedPwd = await bcrypt.genSalt().then(salt => {
  return bcrypt.hash("password", salt);
})

is that you want?

Upvotes: 0

Related Questions