Tiff
Tiff

Reputation: 41

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!

Upvotes: 0

Views: 1149

Answers (3)

Harsh Mandalgi
Harsh Mandalgi

Reputation: 204

Elements are recognized by the name parameter on the server side. You need to add a name attribute in the input tag.

Upvotes: 1

raman077
raman077

Reputation: 157

Give the input element a name attribute as "name" and the code will work fine.

Upvotes: 1

Niklas Higi
Niklas Higi

Reputation: 2309

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").

Upvotes: 4

Related Questions