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

Time:05-31

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

CodePudding user response:

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) {
        //...
     }
}

CodePudding user response:

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

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