0

I got these errores when I try to post the http://localhost:5000/user/login url with postman

Error: Illegal arguments: string, undefined at _async (C:\Users\Raghava\Desktop\react_vite\server\node_modules\bcryptjs\dist\bcrypt.js:286:46) at C:\Users\Raghava\Desktop\react_vite\server\node_modules\bcryptjs\dist\bcrypt.js:307:17 at new Promise () at Object.bcrypt.compare (C:\Users\Raghava\Desktop\react_vite\server\node_modules\bcryptjs\dist\bcrypt.js:306:20) at C:\Users\Raghava\Desktop\react_vite\server\router\UserRouter.js:106:34 at processTicksAndRejections (internal/process/task_queues.js:93:5)

server.js

const express = require("express");
const cors = require("cors");
const dotenv = require("dotenv");
const mongoose = require("mongoose");

const authroute = require("./router/UserRouter");

//config the express
const app = express();

//config the cors
app.use(cors());

//config the body-parser
app.use(express.json());
app.use(express.urlencoded({ extended: false }));

//config the .env
dotenv.config({ path: "./config/config.env" });

//port
const port = 5000;

//connect to database
mongoose
  .connect(process.env.MONGO_DB_URL, {
    useNewUrlParser: true,
    useUnifiedTopology: true,
  })
  .then(() => console.log("connected to database successfully..."))
  .catch((err) => console.log(err));

//config the routes
app.use("/user", authroute);

//starting the server
app.listen(port, () => {
  console.log(`server is started at posrt ${port}`);
});

userRouter.js

const express = require("express");
const Router = express.Router();
const User = require("../models/User");
const bcrypt = require("bcryptjs");
const gravatar = require("gravatar");
const jwt = require("jsonwebtoken");
const { check, validationResult } = require("express-validator/check");


Router.post(
  "/register",
  [
    check("name").notEmpty().withMessage("name is required"),
    check("email").isEmail().withMessage("proper email is required"),
    check("password")
      .isLength({ min: 6 })
      .withMessage("min 6 chars for password"),
  ],
  async (req, res) => {
    let errors = validationResult(req);
    //if error containes
    if (!errors.isEmpty()) {
      return res.status(400).json({
        errors: errors.array(),
      });
    }
    try {
      let { name, email, password } = req.body;
      //user exist
      let user = await User.findOne({ email });
      if (user) {
        return res.status(400).json({
          errors: [{ msg: "user alredy exist" }],
        });
      }
      //encrypt the password
      let salt = await bcrypt.genSalt(10);
      password = await bcrypt.hash(password, salt);
      //get the avatar
      let avatar = gravatar.url(email, {
        s: "200",
        r: "pg",
      });
      //store the user
      user = new User({ name, email, password, avatar });
      await user.save();
      //json web token
      let payload = {
        user: {
          id: user.id,
        },
      };
      jwt.sign(payload, process.env.JWT_SECRET_KEY, (err, token) => {
        if (err) {
          throw err;
        }
        res.status(200).json({
          result: "success",
          token: token,
        });
      });
    } catch (error) {
      console.error(error);
      res.status(500).json({
        errors: [{ msg: error.message }],
      });
    }
  }
);

Router.post(
  "/login",
  [
    check("email").isEmail().withMessage("proper email is required"),
    check("password").notEmpty().withMessage("password is required"),
  ],
  async (req, res) => {
    let errors = validationResult(req);
    //if error containes
    if (!errors.isEmpty()) {
      return res.status(400).json({
        errors: errors.array(),
      });
    }
    try {
      let { email, password } = req.body;
      //check for email
      let user = await User.findOne({ email });
      if (!user) {
        return res.status(400).json({ errors: [{ msg: "invalid credentials" }] });
      }

      //compare password
      let isMatch = await bcrypt.compare(password, user.password);
      if (!isMatch) {
        return res.status(400).json({ errors: [{ msg: "invalid credentials" }] });
      }
      //json web token
      let payload = {
        user: {
          id: user.id,
        },
      };
      jwt.sign(payload, process.env.JWT_SECRET_KEY, (err, token) => {
        if (err) {
          throw err;
        }
        res.status(200).json({
          result: "success",
          token: token,
        });
      });
    } catch (error) {
      console.error(error);
      res.status(500).json({
        errors: [{ msg: error.message }],
      });
    }
  }
);

module.exports = Router;

    
3
  • Try adding the return keyword before res.status(400).json({ errors: [{ msg: "invalid credentials" }] }); This might fix it as it might keep going even after you send the response back. This also fixes another issue with express that I won't explain. Commented Jun 4, 2021 at 18:23
  • 1
    Also, please add a comment to indicate where the error is so users can help you faster. Commented Jun 4, 2021 at 18:25
  • I had the same error. Since I was using elasticsearch as database and I was in the early stages of working with this database, my (find user) query was returning a json object with a lot of elements one of which was user object. So my user.password was undefined. I'm not sure if your problem is the same, but try to log User.findOne() result in the console to check if user.password is referring correctly. I'm sure your problem should be sold very long before, but I'm sharing the comment so that it may helps someone else... Commented Dec 5, 2021 at 7:31

5 Answers 5

0

It's most likely throwing and error because your code does not return after you check if the user exists:

let user = await User.findOne({ email });
if (!user) {
   res.status(400).json({ errors: [{ msg: "invalid credentials" }] });
   // most likely still runs code after this because it is not returning.
}

Please add the return keyword before res.status(400).json({ errors: [{ msg: "invalid credentials" }] }).

Final Code:

if (!user) {
   return res.status(400).json({ errors: [{ msg: "invalid credentials" }] });
}

Additionally, I looked over your code before the error. You do await bcrypt.genSalt(10) and await bcrypt.hash(password, salt). If you take a look at the documentation, you need to passing in a callback for the async version. If you want to use the sync version and not use a callback, please do, bcrypt.genSaltSync() and bcrypt.hashSync().

Sign up to request clarification or add additional context in comments.

5 Comments

Your last comment is incorrect: you can await genSalt because if you don't pass a callback, it returns a promise. github.com/kelektiv/node.bcrypt.js#with-promises
Do not just use the Sync methods here. bcrypt is slow and this will negatively impact performance under any real load.
@Joe sorry, just forgot this is bcryptjs
@hexerous added return keyword before res.status(400).json({ errors: [{ msg: "invalid credentials" }] }). but still i am getting same error
@B.RAGHAVA can you share line 106 at UserRouter.js
0

You need to modify the return of User.FindOne because this user has no password. then in let is Match user.password is going to be undefined. Make a console.log after user and see if it has or not password.

Comments

0

If for some reason the password field is empty, then this error comes.

Check whether the email and password fields are empty or not if one of them is empty then respond back

if (!email || !password) {
    return res.status(400).json({ massage: "Fill up all the form field" });
  }

hope this will fix your problem

Comments

0

first, get the password user model and then compare the password

const getUserPass = await User.findOne({ email }).select("password");

const isMath = await bcrypt.compare(password, getUserPass.password); 

Comments

0

password sending should be a string, there is a probability you send passwords as just numbers

password = await bcrypt.hash(password.toString(), salt);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.