简体   繁体   中英

Pattern to run middleware only for certain routes in Express

What's the best way to configure my Middlewares so that it only runs for certain end points?

Is it best to add that Middleware to each end point one by one Or is there a better way to create configs that can handle it?

you could add as many functions in the route as you want:

for example, using bodyParser middleware for specific route could be done this way:

app.get('/page/:id?/:page?', bodyParser.urlencoded({ extended: false, limit: '50mb' }), function (req, res) {
     .....
}); 

read more in the middleware documentation: http://expressjs.com/guide/using-middleware.html#middleware.router

The best way is to use express group routes find it here and you create an middleware for exmple `

var loginMiddelware = function(req,res,next){
    if(req.session.user){
        next();
    }else{
        res.redirect('/login');
    }
}

And this middelware use in route group like

app.group("/dashboard",(router) => {
    router.use(loginMiddelware);
    router.get('/', dashboardController.index); //url is /dashboard/
    router.get('/profile', dashboardController.profile); //url is /dashboard/profile

});

Hope it works for you.

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