Exclude route from express middleware

前端 未结 8 1579
被撕碎了的回忆
被撕碎了的回忆 2020-12-05 02:40

I have a node app sitting like a firewall/dispatcher in front of other micro services and it uses a middleware chain like below:

...
app.use app_lookup
app.u         


        
相关标签:
8条回答
  • 2020-12-05 03:40

    You can also skip route like this by putting a condition on req.originalUrl:

    app.use(function (req, res, next) {
    
        if (req.originalUrl === '/api/login') {
        return next();
        } else {
             //DO SOMETHING
        }
    
    0 讨论(0)
  • 2020-12-05 03:41

    There's a lot of good answers here. I needed a slightly different answer though.

    I wanted to be able to exclude middleware from all HTTP PUT requests. So I created a more general version of the unless function that allows a predicate to be passed in:

    function unless(pred, middleware) {
        return (req, res, next) => {
            if (pred(req)) {
                next(); // Skip this middleware.
            }
            else {
                middleware(req, res, next); // Allow this middleware.
            }
        }
    }
    

    Example usage:

    app.use(unless(req => req.method === "PUT", bodyParser.json()));
    
    0 讨论(0)
提交回复
热议问题