简体   繁体   中英

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);
    }
});

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-Type s -- 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM