Search code examples
javascriptnode.jsexpressecmascript-6multer

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


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

Solution

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