How do i add multer middleware to my express controller NOT in the router

Viewed 140

This is the format I use to write controllers and routes in Express

controller

exports.postBlog = async (req, res, next) => {...}

routes

router.route("/post").post(onlyAdmin, postBlog);

*onlyAdmin is a protection middleware

I want to add the multer method below in the controller just before the async (req, res, next) so that the uploading logic is handled by the controller not the router

upload.single("image")
2 Answers

Since route handlers accept arrays too, you can to this:

exports.postBlog = [
  upload.single("image"),
  async (req, res, next) => {...}
];

call multer upload middleware from the controller:

const multer = require('multer');
const upload = multer().single('image');

exports.postBlog = async (req, res, next) => {

     upload(req, res, function (err) {
        //...
     }
}
Related