6

How do i retrieve a single field value from the "val" param with busboy?

.js

app.post('/somewhere', (req, res) => {
    req.busboy.on('field', function(fieldname, val) {
       //var foo = val.name;
       //var bar = val.number;
    });
});

.html

<input type="text" name="name"><br>
<input type="tel" name="number"><br>

According to busboy git:

field [...] Emitted for each new non-file field found.

Using the provided example, i was able to identify that 'var' consists of two strings:

typeof(val) 

string
string

But after that i'm clueless in:

  1. What is val in this scope? A var? array? something else?
  2. How do i acess a specific element from val? Like the 'name' field.
Nick
  • 729
  • 8
  • 18

1 Answers1

7

Busboy works with events, so the proper way to get a specific element from your form is to implement on your own a structure that holds form data.

app.post('/somewhere', (req, res) => {

  let formData = new Map();
  req.busboy.on('field', function(fieldname, val) {
    formData.set(fieldname, val);
  });

  req.busboy.on("finish", function() {

    console.log(formData) // Map { 'name' => 'hi', 'number' => '4' }
    // here you can do 
    formData.get('name') //  'hi'
    formData.get('number') //  '4'

    // any other logic with formData here

    res.end()
  });
});

I am not sure what you mean with typeof val but in my case, val is always a simple string

Alex Michailidis
  • 4,078
  • 1
  • 16
  • 35
  • why did you use a Map here rather than just a straight object? I thought a Map had to have consistency in it's stored types, whereas a form might include all kinds of stuff... – dcsan Apr 30 '18 at 18:32
  • 1
    Sure, it could be a plain object. I used a Map in order to have a similar API as [browser's formData](https://developer.mozilla.org/en-US/docs/Web/API/FormData) for uniformity reasons. Also I don't think Maps have to have only one type of data, in fact they can have anything even functions as keys. – Alex Michailidis May 01 '18 at 07:16