-1

I am building a login app using react js node js(express, JWK) but I have a problem when I export my function I recive the error ReferenceError: req is not defined but how I defined req???

This user.router.js:

const { verifyToken } = require("../middleware/authJwt");
const controller = require("../controllers/user.controller");

module.exports = function(app) {
  app.use(function(req, res, next) {
    res.header(
      "Access-Control-Allow-Headers",
      "x-access-token, Origin, Content-Type, Accept"
    );
    next(req);
  });

  app.get(
    "/api/test/user",
    [verifyToken],
    (controller.userBoard)
  );

};

This is authJwt.js:

const jwt = require("jsonwebtoken");
const config = require("../config/auth.config.js");

verifyToken = (req, res, next) => {
  let token = req.headers["x-access-token"];

  if (!token) {
    return res.status(403).send({
      message: "Sem Token"
    });
  }

  jwt.verify(token, config.secret, (err, decoded) => {
    if (err) {
      return res.status(401).send({
        message: "Sem autorização!"
      });
    }
    req.userId = decoded.id;
    next();
  });
};


module.exports = verifyToken();
J.F.
  • 13,927
  • 9
  • 27
  • 65
Pedrohhcunha
  • 41
  • 1
  • 6
  • Look closely: what are you attempting to export? You’re not exporting `verifyToken`. – Sebastian Simon Aug 03 '21 at 20:14
  • Does this answer your question? [What is the difference between a function call and function reference?](https://stackoverflow.com/questions/15886272/what-is-the-difference-between-a-function-call-and-function-reference) – Sebastian Simon Aug 03 '21 at 20:14

1 Answers1

1

You're not exporting verifyToken in authJwt.js. You are exporting a call to this function as a default.

Change

module.exports = verifyToken();

to

module.exports = { verifyToken };

This way you will simply export the reference.

Tomek Buszewski
  • 7,659
  • 14
  • 67
  • 112