Search code examples
node.jsauthenticationcompareruntime-errorbcrypt

ERROR while trying to compare passwords in backeng - NODE.JS


I'm trying to compare password for a login auth, not successfully.

I'm using bcryptjs, installed on server folder.. and I keep getting this error:

Parser.js:437
      throw err; // Rethrow non-MySQL errors
      ^

TypeError: bcrypt.compare is not a function

same error for bcryptSync, and for genSalt.. (tried to be sure...) bcrypt.hashSync is working though.

Any ideas???

Here is my code (I exclude some irrelevant parts):

const express = require("express");
const mysql = require("mysql");
const cors = require("cors");

const bcrypt = ('bcryptjs');

const app = express();

app.use(cors());
app.use(express.json());

// Create connection

const db = mysql.createConnection({
  user: "root",
  host: "localhost",
  password: "1234",
  database: "dashboardDB",
});

// Connect
db.connect((err) => {
  if (err) {
    console.log(err + " Connection error");
  } else {
    console.log("MySql Connected...");
  }
});

app.post("/login", (req, response) => {
  const email = req.body.email;
  const password = req.body.password;

  if (email && password) {
    db.query(
      "SELECT * FROM users WHERE email = ? LIMIT 1",
      [email],
      (err, result) => {
        console.log(result);
        if (err) {
          console.log(err);
        } else if (result.length > 0) {

          bcrypt.compare(password, hash, (err, res) => {
            console.log(err, res);
        });
        

Solution

  • Like @Joe wrote:

    const bcrypt = ('bcryptjs'); should be const bcrypt = require('bcryptjs');