Search code examples
node.jsexpressmulter

Multer not populating request body


My web app is making a post request in the form of a multipart form with 2 text fields and one file.
I am able to access the file data perfectly fine via req.file, however the request body is always undefined.
I found some posts suggesting to re-arrange the fields so that the file is the last piece of data in the form... this did not solve the issue either!
Making the post request from front-end

  uploadData(fileToUpload, xx, yy) {
    const URL = 'http://localhost:5000/api/files/';
    this.setState({ uploadingFile: true });
    let formData = new FormData();
    formData.append('testx', xx);
    formData.append('testy', yy);
    formData.append('file', fileToUpload);

    fetch(URL, {
      method: 'POST',
      body: formData,
    })

Back End handling of request

const multer = require('multer');
const upload = multer({
  dest: 'labels/',
  fileFilter: function (req, file, cb) {
    if (file.mimetype !== 'application/pdf') {
      return cb(null, false, new Error('Incorrect file type'));
    }
    cb(null, true);
  },
  limits: { fileSize: 100000 },
}).single('file');
...
...
...
router.post('/', checkRequestType, upload, (req, res) => {
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      console.log('We got a multer error boys');
      console.log(err);
      return res.send('Error with multer');
    } else if (err) {
      console.log('Error - not caused by multer... but during upload');
      return res.send('Unknown error during upload');
    }
    //Always null here?!?!
    console.log(req.body);
  });
});

Solution

  • There are a couple of issues here. The main one is that you are calling upload twice. The first as a middleware and then you are calling it a second time manually (so that you can handle errors).

    You need to change

    router.post('/', checkRequestType, upload, (req, res) => {
    

    to this

    router.post('/', checkRequestType, (req, res) => {
    

    That should fix the null body issue.

    A second issue is that you are passing too many parameters to the cb in this line return cb(null, false, new Error('Incorrect file type')). The first parameter should be the error: return cb(new Error('Incorrect file type'))