Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Is it possible to disable/remove a middleware for specific route in ExpressJS?

Is it possible to disable/remove a middleware for specific route in ExpressJS?

Problem

I want to disable a Specific middleware, which I've set up previously in the app.js, for example:

app.use(express.bodyParser());

And then I want to remove that bodyParser() for a specific route for instance:

app.post("/posts/add", Post.addPost);

Thank you

Problem courtesy of: mrblue

Solution

You could write a function to detect a condition, like this:

function maybe(fn) {
    return function(req, res, next) {
        if (req.path === '/posts/add' && req.method === 'POST') {
            next();
        } else {
            fn(req, res, next);
        }
    }
}

And then modify the app.use statement:

app.use(maybe(express.bodyParser()));
Solution courtesy of: Werner Kvalem Vesterås

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Is it possible to disable/remove a middleware for specific route in ExpressJS?

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×