Search code examples
node.jsexpressmiddleware

Using 2 middleware functions in one post


Is there any way to use 2 middleware functions like this:

route.post('/login', auth.isAuthenticated, multer.any(), function(req,res) {
  res.send("bla bla bla");
}

Can I use both auth.isAuthenticated and multer.any() (for uploading files)?


Solution

  • You should be able to pass an array of middleware callbacks you'd like to have executed like this according to the docs:

    http://expressjs.com/en/4x/api.html#router.METHOD

    router.METHOD(path, [callback, ...] callback)

    route.post('/login', [auth.isAuthenticated, multer.any()], function(req, res) {
        res.send("bla bla bla");
    });
    

    Update:

    You may need to structure where all callbacks are within the array brackets []:

    route.post('/login', [auth.isAuthenticated, multer.any(), function(req, res) {
        res.send("bla bla bla");
    }]);
    

    You could also consider using app.use() to register callbacks like so:

    var route = express.Router();
    
    var require = require('multer');
    var upload = multer({ dest: '/some/path' });
    
    route.use(auth.isAuthenticated);
    route.use(upload.any());
    
    app.use("/login", route);
    

    Hopefully that helps!