简体   繁体   中英

Unexpected identifier Syntax Error when using mysql and bcryptjs

I'm using Mysql in my Express app i hashed users pass using bcryptjs in mysql db and its fine. using this code :

// register
router.post("/register", async (req, res) => {
  const hashed = await bcrypt.hash(req.body.pass, 10);
  const user = {
    uname: req.body.uname,
    phone: req.body.phone,
    pass: hashed
  };
  let sql = "INSERT INTO user SET ? ";
  db.query(sql, user, (err, result) => {
    if (err) throw err;
    console.log(`${user.uname} INSERTED INTO users`);
  });
});
// GET USERS
router.get("/users", (req, res) => {
  db.query("SELECT * FROM user", (err, results) => {
    if (err) {
      return res.send(err);
    } else {
      return res.json({
        data: results
      });
    }
  });
});

but when i want to log in users and let bcrypt compare requested pass with user pass it will give me this err : SyntaxError: Unexpected identifier

And this is what i tried :

// loggin
router.post("/login", async (req, res) => {
  var username = req.body.uname;
  var password = req.body.pass;
  db.query(
    "SELECT pass FROM user WHERE uname = ?",
    [username],
    (err, result, fields) => {
      try {
        if (await bcrypt.compare(password, result)) {
          console.log('Success')
        }
      } catch {
        console.log('catched')
      }
    }
  );
});

💡 The only one reason why you got some error, it's because you're using await in a function without async

👨🏻‍🏫 You can use this code below 👇:

router.post("/login", async (req, res) => {
  var username = req.body.uname;
  var password = req.body.pass;
  db.query(
    "SELECT pass FROM user WHERE uname = ?",
    [username],
    async (err, result, fields) => {
      try {
        // if you're using mysql2, don't forget to change `result` with `result[0].pass`.
        // you can console.log(result) to see where is the field of your password plain text
        const isPassword = await bcrypt.compare(password, result);
        console.log(isPassword); // true
      } catch(ex) {
        console.log(ex); // false
      }
    }
  );
});

I hope it's can help you 🙏.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM