1
votes

I'm new to NodeJS, I'm developing app where I have created registeration form. To upload images, I'm using multer. And for form validation I'm using express-validator. The issue with me is that, before form validation, file has upload. So, if user hasn't created account because of some validation errors, but file goes upload. The problem is that I get file upload for each form submition no matter, account has successfully created or not.

What I want to do?

I want save file only when user has successfully created account. So, is there anyway to use multer inside callback, so when my form validations are done, then files goes upload. I can't use express-validation middleware between multer midleware and final callback, because express-validation passes it's errors to next call back. Here is my some code

router.post('/registeration', multerMiddleware, validationMiddleware, finalCallback)

validationMiddleware is an array.

var multer = require('multer');
var multerMiddleware= multer({dest: './profile-images', fileFilter: userRegisteration.fileFilter}).single('profileImage');
var validationMiddleware = [check(...), check(...),...]
var finalCallback = function (req, res, next) {
 // code is here
}
1

1 Answers

1
votes

Express router executes the middlewares in the same sequence you mount them

router.post('/registeration', multerMiddleware, validationMiddleware, finalCallback)

So, your multerMiddleware is executed ( and hence saved the file ) before your validationMiddleware has done the validation.

Change the code to:

router.post('/registeration', validationMiddleware,multerMiddleware, finalCallback)

So, multerMiddleware will only save file once the request is validated