Home > database >  Why is my "req" undefined? "TypeError: Cannot read property 'headers' of un
Why is my "req" undefined? "TypeError: Cannot read property 'headers' of un

Time:12-24

I am trying to implement authentication middleware to my routes in an Express Router.

When the router goes to the middleware and tries to read the req.headers["authorization"], I get the error:

const authHeader = req.headers["authorization"];
                         ^
TypeError: Cannot read property 'headers' of undefined

I'm not sure what I'm missing here, I've gone through the Express router middleware but couldn't find my answers there.

I have also tried not calling router.use(authenticateToken()); like this router.use(authenticateToken); and get this error: TypeError: Router.use() requires a middleware function but got a Object

Below is the middleware function and the route that I tried to use it on. Here is the project on GitHub in its current state.

// Authenticate Token!
authenticateToken = function (req, res, next) {
  const authHeader = req.headers["authorization"];
  console.log(authHeader);
  const token = authHeader && authHeader.split(" ")[1];
  if (token == null) {
    return res.sendStatus(401);
  } else {
    jwt.verify(token, process.env.ACCESS_TOKEN_SECRET, (err, username) => {
      if (err) {
        return res.sendStatus(403);
      } else {
        req.username = username;
        next();
      }
    });
  }
};
router.use(authenticateToken());

router.get("/", authenticateToken, async (req, res) => {
  try {
    const users = await User.find();
    res.status(200).json(users);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

CodePudding user response:

You are incorrectly registering your middleware.

You have

router.get("/", authenticateToken(), async ...

while it should be

router.get("/", authenticateToken, async ...

The first incorrect version of yours tries to immediately call the method. Instead, the method reference should be passed to router so that it's the pipeline that calls you.

CodePudding user response:

I think you should define your middleware like this:

router.get("/", authenticateToken, async (req, res) => {
  try {
    const users = await User.find();
    res.status(200).json(users);
  } catch (err) {
    res.status(500).json({ message: err.message });
  }
});

CodePudding user response:

I figured it out! And sadly, it was unrelated to the code and question I had above.

I was missing the line module.exports = router; at the bottom of the file!

Thanks everyone!

  • Related