question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

req.body become empty object when I added enctype='multipart/form-data' to form

See original GitHub issue

I have a form which sends data to server: text fields and images. Before mounting formidable, my req.body got data which are stored in db. But when I added formidable middleware AND add to form attribute enctype=‘multipart/form-data’ which allows upload files to server, my req.body become just empty object, and, yes, I got uploaded images and vice versa: after removing this attribute, I have full req.body but images wasn’t uploaded.

I also tried to move mounting formidable into route.js file, but this did not help.

I’ve got such project structure:

bookController.js which imported into route.js

var BookEntity= require('../models/bookModel');
var formidable = require('formidable');

exports.addBook = function(req, res){  

      console.log(req.body.large_fotos);
      var largeFotosArray = [];      
      var form = formidable.IncomingForm({
            uploadDir: __dirname + '/uploads', 
            keepExtensions: true
      });
      form.parse(req, function(err, fields, files){
            console.log('INCOMING: ' + files);
      });
      form.on('fileBegin', function(name, file){
            file.path = __dirname + '/uploads/' + file.name;
            largeFotosArray.push(file.path);
      });
      form.on('file', function(name, file){
            console.log('Uploaded: ' + file.name);
      });

      // then saving Book in DB

});
route.js

    var express = require('express');
    var controller = require('../controllers/bookController');

     var subapp = express.Router();

   // included other routes...

     subapp.post('/book/add', function(req, res){
        console.log(req.body);
        controller.addBook(req, res);
    });

Issue Analytics

  • State:closed
  • Created 6 years ago
  • Reactions:4
  • Comments:14 (3 by maintainers)

github_iconTop GitHub Comments

6reactions
ParallelUniv3rsecommented, Nov 29, 2018

Sorry, I forgot to follow-up with a fix. It’s quite simple, just don’t specify the Content-Type in the config yourself if you can. TLDR; setting Content-Type to only multipart/form-data is not enough. the required syntax is multipart/form-data; boundary=<somestring>

IIRC isomorphic-fetch does the work of specifying the correct header of your client-side request for you. I don’t know how about other libraries. If you need to specify it yourself stick to the required syntax as mentioned above. (pay attention to the boundary directive which is required. you can use something like in the example from the comments above

3reactions
TheBeachMastercommented, Jul 20, 2019

@ParallelUniv3rse thanks for this…

Anyone else who experiences this issue in the future and wants a quick workaround… You can do it like this

    const formData =  new FormData();
    formData.append("file", upload.files[0]);
    fetch('/upload',{
      body: formData,
      headers: {
        'Accept' : 'application/json'
      },
      method: 'post'
    })
      .then(data => {
        console.log("Success", data);
        file='';
      })
      .catch(error => {
        console.log("There was a problem", error);
      });
  }

Note that upload is the id of your file input field. Also, note the omission of Content-Type.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Express body-parser req.body with formdata is empty object
Make sure to add enctype="multipart/form-data" on form element. Otherwise Multer will ignore it. let multer = require('multer'); let upload ...
Read more >
The Express + Node.js Handbook
If you're in an empty folder, first create a new Node.js project with this command: npm init -y. then run this: npm install...
Read more >
Sending request with form-data failed! it send an empty ...
Hello community, I need help solving this problem . in this image sending a request is totally normal and I have my data...
Read more >
Request and response objects
Django uses request and response objects to pass state through the system. ... and the <form> that posted to the request had enctype="multipart/form-data"...
Read more >
Axios Multipart Form Data - Sending File Through a ...
Any and all files will be located under the files field of the req object! We can thus access the input username via...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found