Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS Multer validate fields before upload

I'm trying to validation my form before i upload images but i getting empty string on my middleware

const upload = multer({
  storage: storage
});

router.post('/upload', formsValidation, upload.fields([{

  name: 'images',
  maxCount: 20

}, {

  name: 'imageMain',
  maxCount: 1

}]), function(req, res, next) {
  code...

});

heres my middleware:

function formsValidation (req, res, next) {

  console.log(req.body) //getting empty array here
  return next();
}

i know that i can use fileFilter from multer but some times i dont have any images to upload just string to store and validate, i have tried to parse the req.body from multipart/form-data to string then validate and use next() but i get a range error, any ideia how can i solve this?

like image 420
John Avatar asked Jan 09 '18 17:01

John


1 Answers

This is from Multer's docs:

Note that req.body might not have been fully populated yet. It depends on the order that the client transmits fields and files to the server.

That's mean you have to call formsValidation just after multer midlleware, to make sure that all posted data have been fully populated

router.post('/upload', upload.fields([{

    name: 'images',
    maxCount: 20

}, {

    name: 'imageMain',
    maxCount: 1

}]), formsValidation, function(req, res, next) {
    code...
});
like image 190
YouneL Avatar answered Oct 24 '22 02:10

YouneL