Search code examples
node.jsformsbusboy

Get field value from form with busboy


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.

Solution

  • 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