professor_robot
professor_robot

Reputation: 41

nodejs express mounting middleware only for a path

so I have this middleware function:

    function sessionTest(req,res,next){
        if(req.method === 'GET'){
            var signedCookies = req.signedCookies;
            var numValues = Object.keys(signedCookies).length;
            console.log("sessionTest, signedCookies: "+JSON.stringify(signedCookies));
            if(numValues === 0 || signedCookies.user === undefined){
                //redirect user to the login page
                res.render('login', {msg:"Please login"});
            }else{
                next();
            }
        }else{
            next();
        }
    }

I only want to mount it for the '/' path. I have tried: app.use('/',sessionTest); but it does not work and other paths such as '/files' still pick that middleware up.

Upvotes: 0

Views: 226

Answers (1)

KeepCalmAndCarryOn
KeepCalmAndCarryOn

Reputation: 9075

If you only need it for one path you can do this

app.all('/', sessionTest, someOtherFunction, yetAnotherFunction)

and when the next() call is made (if at all) it will cascade through to the next one

Upvotes: 2

Related Questions