Search code examples
node.jsreactjsbcrypt

Node.js error: "undefined No callback function was given"


I am currently learning React by following a course in which we build a video rental app. The backend code is provided by the instructor and our job is to connect the frontend to the backend. When submitting the registration form in the app, I get the following error in Git Bash which is where I started the server: "undefined No callback function was given".

I believe this issue has to do with bcrypt (the instructor used bcrypt-nodejs to encrypt the passwords). Since bcrypt-nodejs has been deprecated, I have installed bcryptjs instead and read the documentation. however, I don't really know how to modify the code to make it work.

If someone could help me with this I would really appreciate it. I'm relatively new to web development and I'm struggling to make this code work.

Many thanks.

Below the backend part that interacts with the registration form:

const bcrypt = require("bcrypt-nodejs");
const _ = require("lodash");
const { User, validate } = require("../models/user");
const express = require("express");
const router = express.Router();

router.get("/", async (req, res) => {
  const users = await User.find();
  res.send(users);
});

router.get("/me", auth, async (req, res) => {
  const user = await User.findById(req.user._id).select("-password");
  res.send(user);
});

router.post("/", async (req, res) => {
  const { error } = validate(req.body);
  if (error) return res.status(400).send(error.details[0].message);

  let user = await User.findOne({ email: req.body.email });
  if (user) return res.status(400).send("User already registered.");

  user = new User(_.pick(req.body, ["name", "email", "password"]));
  const salt = await bcrypt.genSalt(10);
  user.password = await bcrypt.hash(user.password, salt);
  await user.save();

  const token = user.generateAuthToken();
  res
    .header("x-auth-token", token)
    .send(_.pick(user, ["_id", "name", "email"]));
});

module.exports = router;


Solution

  • The correct way to use bcrypt.gensalt is as follows:

    bcrypt.genSalt(saltRounds, function(err, salt) {
        bcrypt.hash(myPlaintextPassword, salt, function(err, hash) {
            // Store hash in your password DB.
        });
    });
    

    Here function(err, salt) stands for the callback function.

    Here is the link for more details on bcrypt and about the callback