2

How do I get array form data using busboy?

In route:

req.busboy.on('field', function(fieldname, val){
  //fieldname is string, expecting array
  //'bunnies[gray]', etc...
});

And my view:

form(method="post" action="/post/path" enctype="multipart/form-data")
    input(name="bunnies[gray]")
    input(name="bunnies[white]")
    input(name="bunnies[black]")
    input(name="bunnies[brown]")
    input(name="bunnies[purple]")
Randy Hall
  • 7,716
  • 16
  • 73
  • 151

3 Answers3

1

So busboy isn't stupid -- multipart/form-data does not by default support arrays in the same way as a JSON body does.

Requests with arrayName[n] as field names will not be parsed as arrays by busboy alone -- such a payload will have still have to be parsed manually.

One can manually parse these array values using one of these other answers...

... but if manually parsing arrays is undesired, one may consider using co-busboy instead using this option:

autoFields: true
jiminikiz
  • 2,867
  • 1
  • 25
  • 28
-1

The question is rather old, but in case someone else stumbles upon this problem, here's what I did:

var arr = new Array();

req.pipe(req.busboy);

req.busboy.on('field', function(key, value) {
  if(key === 'array_name[]') {
    arr.push(value);
  }
});

req.busboy.on('finish', function() {
  console.log(arr);
});
VF_
  • 2,627
  • 17
  • 17
-1

Question if 5 years old but it gave me a hint. I am coming from PHP background and didn't realize that Busboy is this stupid, so if you want to process array of fields, you need to actually process them like this:

busboy.on('field', (fieldname, val) => {
    if (fieldname.indexOf('[]') !== -1) {
        let fn = fieldname.replace('[]', '');
        if (typeof req.body[fn] === 'undefined') {
            req.body[fn] = [];
        }
        req.body[fn].push(val);
    } else {
        req.body[fieldname] = val;
    }
});

Hope to save someone else a few hours of debugging ...

Kristjan O.
  • 814
  • 1
  • 9
  • 33