node.jsformsexpressparsingbody-parser

Data is always 'undefined' when POSTing form data through body-parser in node.js express


I've stripped down the form to the following for clarity:

      <form method="post" action="/form" id="testform" enctype="application/x-www-form-urlencoded" name="testform" novalidate>
          <input type="text" class="form-control" id="name" >
          <button type="submit" class="btn btn-dark btn-lg">Generate XML</button>
      </form>

in my main js file I have the following:

var bodyParser = require('body-parser')

// create application/x-www-form-urlencoded parser
var urlencodedParser = bodyParser.urlencoded({ extended: true })

and I'm receiving the data (or not, as the case may be) here:

.post('/form', urlencodedParser, function (req, res) {
    res.send('welcome, ' + req.body.name)
    console.log(req.body)
  })

and all I'm getting is "welcome, undefined", and the log is showing empty - {}

This is driving me insaaaaaaaaane how do I inspect what's sent? Debugging this is madness!


Solution

  • I think you're missing the name attribute on the <input> element:

    <input type="text" class="form-control" id="name"  name="name">
    

    You've already set an id but that can only be used for CSS selectors (#name), links (visiting #name will select that input) and <label> elements (using for="name").