Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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">
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading