Search code examples
javascriptnode.jsexpressmulter

How to optionally insert middleware (multer) into new express router


In an older project, I setup a router and use multer to handle file uploads. I am able to use multer middleware on certain routes selectively like this:

var router = express.Router();
var multer = require('multer');
var upload = multer({dest:'./tmp/'}).single('file');

router.post('/:id/foo', upload, function(req, res, next) {
    // req.file is the path to a file that can be read from tmp
    // ...
});

Recently, I used a yeoman generator to make node api app, and I'd like to add file uploading via multer to that, too. But how do I do that in this new app's structure, which uses a new way to setup routes?

It's index.js file looks like this:

// ...
const routes = require('./routes');
//...
app.use('/', routes);

In routes.js it does this:

const Router = require('express').Router;
const router = new Router();

const user = require('./model/SomeModel/router');
//...
module.exports = router;

And in ./model/SomeModel/router.js, I added some routes following the pattern that was already in the file, using ...args like this:

// In some of these, I want to insert multer, but where?
router.route('/doSomething')
  .post((...args) => controller.doSomething(...args));

module.exports = router;

I think my problem is that ...args syntax. How do I get multer inserted into the chain of middleware with the args?


Solution

  • You can mount middleware on specific routers:

    router.use(upload) // runs for all routes mounted under this call
    router.route('/doSomething')
      .post((...args) => controller.doSomething(...args));
    
    module.exports = router;
    

    You should also be able to put it before your post callback:

    router.route('/doSomething')
      .post(upload, (...args) => controller.doSomething(...args));