Home > OS >  Compare the username and password in reactjs using bcrypt
Compare the username and password in reactjs using bcrypt

Time:11-24

I am trying to compare the username and password for may auth. then i think everything is good at my code but it throws me an error if the username and password is incorrect and the nodejs is stopping this error give me [Here is my error] (https://i.stack.imgur.com/OSxpK.png)

and this is my code what I did in this code Im trying to compare the username and password

router.post("/login", async (req, res) => {
    const {username, password} = req.body;

    const user = await Admin.findOne({where: {username: username}});

    if (!user) res.json({error: "Admin User doesn't exist"});

    bcrypt.compare(password, user.password).then((match) => {
        if(!match) res.json({error: "Username and password is incorrect"});
        res.json("Login Success");
    });
});

your text

CodePudding user response:

I Solve the my problem here is my code

router.post("/login", async (req, res) => { const {username, password} = req.body;

const user = await Admin.findOne({where: {username: username}});

if (!user) return res.status(400).json({error: "Admin User doesn't exist"});

bcrypt.compare(password, user.password).then((match) => {
    if(!match) return res.status(400).json({error: "Username and password is incorrect"});
    res.json("Login Success");
});

});

CodePudding user response:

Put a try catch and check the logs the node js terminal

router.post("/login", async (req, res) => {
   try {
      const {username, password} = req.body;

      const user = await Admin.findOne({where: {username: username}});

      // make sure the user password was hashed befor saving
      // const hashPassword = await hash(password, await genSalt());

      if (!user) res.json({error: "Admin User doesn't exist"});

      const match = await bcrypt.compare(password, user.password)
        if(!match) {
            res.json({error: "Username and password is incorrect"});
        else {
            res.json("Login Success");
        }
    }
  } catch(error) {
     // App logger log
     //check console in node terminal
     console.error('error authenticating', error)
     // return 500 http status code or may be a code 
     // depending on how you are handling it in the client
  } 

});
  • Related