Nano
Nano

Reputation: 847

express router middleware: reference error "req is not defined"

Im working with a middleware that authenticate a token, but the probolem isn't the snippet, the problem stars when I instantiate the function.

There is my code:

router.use(authRequirer(req, res, next));

Sure, here is the routing file:

let router = express.Router();

// Middleware
import authRequirer from '../util/authRequirer';

// Controllers
import AuthCtrl from '../controllers/authCtrl';
import UserCtrl from '../controllers/userCtrl';

let authCtrl = new AuthCtrl();
let userCtrl = new UserCtrl();

router.get('/', (req, res) => {
  res.json({ message: "Hey, im working" });
});

// Login, Register, setup admin
router.get('/setup'    , authCtrl.setup);
router.post('/register', authCtrl.register);
router.post('/login'   , authCtrl.login);

// Autenticacion requerida
router.use(authRequirer(req, res, next));

router.route('/users')
  .get(userCtrl.getAll)
  .post(userCtrl.create);

router.route('/users/:username')
  .get(userCtrl.getOne)
  .put(userCtrl.edit)
  .delete(userCtrl.delete);

export default router;

I think that i don't do any out of the normal, but when i run the code, it throws me the following trace:

/home/nano/Dev/omgfriki-api/app/routes/apiroutes.js:44
router.use((0, _utilAuthRequirer2['default'])(req, res, next));
                                              ^
ReferenceError: req is not defined

Why req isn't defined? As far as I understand, it is defined when you call router.

Anyway, i'm using Babel with a require hook to compile the things, but 90% that it's not the problem.

Upvotes: 0

Views: 7131

Answers (1)

Wilson
Wilson

Reputation: 9136

Instead of invoking the authRequirer function with variables like req, res, and next that don't exist yet:

router.use(authRequirer(req, res, next));

You should pass only the function:

router.use(authRequirer);

Because the use method is the one who is going to invoke your authRequirer function passing by the req, res, and next parameters.

Upvotes: 5

Related Questions