Req is unidefined, Anyone know this?? please help me

Issue

i create the Class namely UserService and in which i added the method of login , but i don’t know why req and body both are undefined

UserService.js

const user =require("../../database/models/usermodal")
var bodyParser = require("body-parser");
var jsonParser = bodyParser.json();
const bcrypt = require("bcryptjs");

const jwt = require("jsonwebtoken");
const {
    registerValidation,
    loginValidation,
  } = require("../validators/validation");
  const verify = require("../validators/verifytoken");
  const { any } = require("@hapi/joi");

class UserService {
    // create = async (data) => await user.create(data);
    getById = async (email) => await user.findOne({where:{email}});

    onlogin= async (req, res) => {
      

        const { error } = loginValidation(req.body);
    
        // validate:
        if (error) return res.status(400).send(error.details[0].message);
    
        // check the email
        const emailExist = await user.findOne({where:{email:req.body.email}});
    
        if (!emailExist)
          return res.status(400).send("Email Not found or password is incorect");
        // Password checeking:
        const validPass = await bcrypt.compare(
          req.body.password,
          emailExist.password
        );
        if (!validPass) return res.status(400).send("Invalid Password");
    
        const token = jwt.sign(
          { id: emailExist.id, first_name: emailExist.first_name, last_name:emailExist.last_name, email: emailExist.email },
          env.Variable.JWT
        );
          //  res.body(token)
        res.header("Auth-token", token).send(token);
      };

      onsignup=async (req, res) => {
        console.log(req)
        const { error } = registerValidation(req.body);
    
        // validate:
        if (error) return res.status(400).send(error.details[0].message);
    
        // check the user if the email is already exist:
        const emailExist =  await user.findOne({where:{email:req.body.email}});
        console.log(emailExist);
        if (emailExist) return res.status(400).send("Email already exist");
    
        // hashing the password:
        const salt = await bcrypt.genSalt(10);
        const hashPassword = await bcrypt.hash(req.body.password, salt);
       
        const users = user.create({
          first_name: req.body.first_name,
          last_name: req.body.last_name,
          is_delete: req.body.is_delete,
          google_auth_token: req.body.google_auth_token,
          refresh_token: req.body.refresh_token,
          email: req.body.email,
          password: hashPassword,
        });
    
        res.status(200).json({
          success: true,
          data: users,
        });
      };
    
     

}

module.exports = new UserService();

It just listens on the localhost on port 9090 and logs the body of the request into the console. When I send any request through Postman,]it outputs "undefined". Why is this? Is this a problem with my code or with my usage of Postman?

you can check my ERROR here

userContorller.js

const userService = require("../../services/userService");
const express = require("express");

// const {
//   registerValidation,
//   loginValidation,
// } = require("../../validators/validation");
const verify = require("../../validators/verifytoken");
// const { any } = require("@hapi/joi");

const env=require("../../../config/config");
// const { use } = require("../../routes/userRoute");

class UserController {
  onSingups = async()=>{
    await userService.onsignup()
  }
  onlogin = async()=>{
    await userService.onlogin();
  }

  onGetAllUsers = async (req, res) => {
    const users = await userService.getAll();
    res.status(200).json({
      success: true,
      data: users,
    });
  };
}

module.exports = new UserController();

userRoute.js

const express = require("express");
const userControllar = require("../controllers/public/userController");
const bodyParser=require("body-parser")
const verify=require("../validators/verifytoken")
var jsonParser = bodyParser.json()


const router =express.Router();

router.route("/").get(userControllar.onGetAllUsers);
router.route("/singup").post(jsonParser,userControllar.onSingups);
router.route("/login").post(jsonParser,userControllar.onlogin);
router.get("/data",verify,(req,res)=>{
    res.send(req.user)
})



module.exports=router;

Solution

you should add the req & res in controller

class UserController {
  onSingups = async(req, res)=>{
    await userService.onsignup(req, res)
  }
  onlogin = async(req, res)=>{
    await userService.onlogin(req, res);
  }

  onGetAllUsers = async (req, res) => {
    const users = await userService.getAll();
    res.status(200).json({
      success: true,
      data: users,
    });
  };
}

Answered By – Sonu Sindhu

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published