0

I was trying to get the user data from my database, but what I get is req.body is undefined, I can't fix the problem and I need help.

Error : TypeError: Cannot read properties of undefined (reading '_id')

my code:

user.js

const express = require("express");
const router = express.Router();
const { requireSignin, authMiddleware } = require("../controllers/auth");
const { read } = require("../controllers/user");

router.get("/profile", requireSignin, authMiddleware, read);

module.exports = router;

Auth.js

exports.authMiddleware = (req, res, next) => {
  const authUserId = req.user._id;
  console.log(authUserId);
  User.findById({ _id: authUserId }).exec((err, user) => {
    if (err || !user) {
      return res.status(400).json({
        error: "User not found",
      });
    }
    req.profile = user;
    next();
  });
};

exports.requireSignin = expressjwt({
  secret: process.env.JWT_SECRET,
  algorithms: ["HS256"],
});
6
  • 1
    So req.user is undefined. We can't predict why. Commented Jun 28, 2022 at 11:43
  • How i can approach to solve this problem? Commented Jun 28, 2022 at 12:50
  • At least show us where req.user is supposed to be coming from. Commented Jun 28, 2022 at 12:51
  • @IshtiaqMahmood, you add body parser ? Can you show the code where you integrated the middlewares Commented Jun 28, 2022 at 13:50
  • "The decoded JWT payload is now available as req.auth rather than req.user" Commented Jun 28, 2022 at 13:59

2 Answers 2

1

With v6 of express-jwt, req.user was replaced by req.auth, as documented in the migration notes:

The decoded JWT payload is now available as req.auth rather than req.user

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

Comments

0

You can put an Optional Chaining operator ? In order to avoid “read properties of undefined error”.

const authUserId = req.user._id;

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.