can't call included middleware in express 4's Router.use()

123 views Asked by At

I wrote a function that redirects no authorized users

module.exports = function(req, res, next) {
if (!req.session.authUser) {
    // if AJAX request
    if(req.xhr) 
        helpers.send_failure(not_authorized());
    else
        res.redirect('/');
    return;
} 
else 
    next();
};

and attached it to express 4's router

/// included all necessary modules: express, redirectNotAuthorized etc..

var authRouter = express.Router();
authRouter.use(redirectNotAuthorized());   
app.use('/', authRouter);

But got an error, req is undefined. Even tried to pass arguments myself:

authRouter.use(redirectNotAuthorized(req, res, next));  

but got an error that req is undefined

Then I tried to write redirectNotAuthorized function inside this (router) module, but have an error Router.use() requires middlewarefunctions

If I do it like in Express's guide it works:

router.use(function(req, res, next) {
  res.send('Hello World');
});

But it's not comfortable, because I need to require (include) them in other routers too.

Don't know if it is my falult, or is it a bug. If it is a bug please how I can include same middleware in other routers too. Thanks

0

There are 0 answers