Read form-data on server

I am using multer to upload images to server. To do this, I send a form-data request from the client. It became necessary to check if the user is authorized. To do this, I send an object with a username and password. But there was a problem: I just can’t get this data.

I use body-parser to get the request body.

I usually get the request body like this:

const reqBody = JSON.parse(JSON.stringify(req.body));

With any other request, everything is fine, but with form-data reqBody === {}. What to do?

Route using multer:

router.post('/image_for_profile',
    cors(corsOptions),
    async(req, res) => {
        try {
            const reqBody = JSON.parse(JSON.stringify(req.body));
            console.log(reqBody) // {}

            let status;

            upload(req, res, err => {
                let error = '';

                if (err) {
                    if (err.code === 'LIMIT_FILE_SIZE') {
                        error = 'Размер изображения не должен превышать 2мб';
                    }
                    if (err.code === 'EXTENTION') {
                        error = 'Файл не является ни jpg, ни jpeg, ни png';
                    }
                    status = error;
                }
            });

            return res.status(200).json({
                msg: status || 'OK',
            });
        } catch (err) {
            console.log(err)
            return res.status(500).json({
                msg: config.get('msgs.statuses.500err')
            });
        }
    }
);

The request:

enter image description here

Answer

The problem is that you’re currently trying to access req.body before your form-data-parser has populated it. You need to move this into the upload-callback, multer will then have populated all text-based form-fields under req.body and there under the name of your form-field (data in your case).

// ...
 upload(req, res, err => {
      console.log(req.body.data); // will be populated here
      // ...
});