简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM