Node.JS – Express request returns undefined when when submitting a post request from a form

Advertisements

When I try to get an HTML form from using Node.JS/Express it seems to return a undefined value as the req.body returns an empty object.

Node

const express = require('express')
const bodyParser = require('body-parser')
const app = express()
const port = '3000'


app.use(bodyParser.urlencoded({ extended: true}))


app.use(bodyParser.json());  

app.use(express.static('public'))

app.get('/',function(req, res) {

    res.sendFile( __dirname + '/signup.html')

});

app.post('/', function(req, res) {
const FirstName = req.body.firstName
const LastName = req.body.lastName

console.log(FirstName)
console.log(LastName)

});

app.listen(port, function(err) {
if (err) console.log(err)
console.log('Local port started at', port)
});

HTML

<form action="/" method="post"\>
  <label for="firstName"\>First Name\</label\>
  <input class="form-grid__item--field" type="text" id="firstName" placeholder="First Name"\>

  <label for="lastName">Last Name</label>
  <input class="form-grid__item--field" type="text" id="lastName" placeholder="Last Name">
              
  <label for="subscriberEmail">Email</label>
  <input class="form-grid__item--field" type="text" id="subscriberEmail" placeholder="Email">
          
  <input type="submit" class="form__button" value="Sign Me Up!">
</form>

Reformatted the code several times. Looked into the html form to ensure the action and methods where in place. When over body parser documentation to try and get more context but nothing.

>Solution :

The id field inside input label is used for referencing the element in the DOM.

In order to pass the input as a field in the request you must give it attribute name

 <input class="form-grid__item--field" type="text" id="subscriberEmail" name="subscriberEmail" placeholder="Email">

Leave a ReplyCancel reply