0

As far as I know I need to place multer middleware before express-validator middleware in order to be able to access req.body from express-validator custom validators, like this:

app.post('/editPhoto', 
upload.single('avatar'), 
[express-validator middleware],
(req, res, next) => {
    // req.file 
   //req.body
});

There are 2 options you can use to work with multer:

app.post('/editPhoto', upload.single('avatar'), [express-validator middleware],(req, res, next) => {
   // req.file 
//req.body
})

Or you can use:

app.post('/editPhoto', (req, res, next) => {
  upload(req, res, function (err) {
    if (err) {
      // This is a good practice when you want to handle your errors differently

      return
    }

    // Everything went fine 
  })
})

In the second option, you can handle Multer's errors, I would like to know if I could handle Multer's errors in the express-validator custom validators or in express route handling middleware if I use Multer as a middleware before the express-validator middleware, as in my first example

william
  • 103
  • 1
  • 2
  • 9

2 Answers2

0

This question was answered here If you want to catch multer errors you will have to create a middleware for that or make a general middleware.

// general middle that affects all routes
app.use((err, req, res, next) => {
    if (err instanceof multer.MulterError) { // Multer-specific errors
        return res.status(418).json({
            err_code: err.code,
            err_message: err.message,
        });
    } else { // Handling errors for any other cases from whole application
        return res.status(500).json({
            err_code: 409,
            err_message: "Something went wrong!"
        });
    }
});

then you can continue with the normal multer upload middleware

app.post('/editPhoto', upload.single('avatar'), (req, res) => {// your code});
Etemire Ewoma
  • 133
  • 1
  • 7
-1

I finally solved it creating a function with the multer code where I check for errors (using the second option of the example in my question). I call that function in the middleware chain before all the express-validator middleware functions.

william
  • 103
  • 1
  • 2
  • 9