4

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)?

1 Answer 1

6

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!

Sign up to request clarification or add additional context in comments.

2 Comments

but what if I just wanted to use middleware for only 1 route ? can I handle with that by using route.use(auth.isAuthenticated); I mean that if I do that all my routes will connected to that middleware or it is different ?
You are correct, .use() would be for all HTTP verbs, so it may not be ideal/valid for specific situations. I've updated my answer to show how it would only apply to route "/login". The example I provided would be all HTTP verbs for route "/login" when using use(). Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.