Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get POST fields in Express, without using bodyParser middleware?

With recent versions of Express, the recommendation (conveyed through a debug message) is to stop using the bodyParser middleware. I read a bit, and it looks like bodyParser is a wrapper to the json and urlencoded middlewares - and lo and behold, the most recent version of Express (3.4.4) uses these 2 instead of the bodyParser out of the box - splendid, right?

But now, I can't get to my fields. req.body is undefined. Here's my JS form submission code (text fields only, no files). Could someone please tell me which property/function of req do I use to get at the values?

var formData = new FormData($('#myForm')[0]);
$.ajax({
    url: '/myurl',
    cache: false,
    contentType: false,
    processData: false,
    data: formData,
    type: 'POST',
    success: function(data) {
        console.log(data);
    },
    error: function(jqXHR, textStatus, errorThrown) {
        console.error('Error occured: ' + errorThrown);
    }
});
like image 1000
Traveling Tech Guy Avatar asked Nov 26 '13 21:11

Traveling Tech Guy


1 Answers

The issue is that, when sending FormData, the Content-Type will be multipart/form-data.

Though you're using express.json() and express.urlencoded(), each of them only acts on particular Content-Types -- application/json and application/x-www-form-urlencoded, respectively.

And Express/Connect will be removing built-in support for multipart() and parsing of multipart/form-data content in the future due to security concerns. They instead recommend using:

  • formidable
  • connect-multiparty or multiparty
  • connect-busboy or busboy

So, for future support of FormData and multi-part in general with Express/Connect, you'll have to use an addition dependency.

like image 142
Jonathan Lonowski Avatar answered Oct 02 '22 16:10

Jonathan Lonowski