Home > Software design >  Node.JS - Express request returns undefined when when submitting a post request from a form
Node.JS - Express request returns undefined when when submitting a post request from a form

Time:01-07

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  type="text" id="firstName" placeholder="First Name"\>

  <label for="lastName">Last Name</label>
  <input  type="text" id="lastName" placeholder="Last Name">
              
  <label for="subscriberEmail">Email</label>
  <input  type="text" id="subscriberEmail" placeholder="Email">
          
  <input type="submit"  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.

CodePudding user response:

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  type="text" id="subscriberEmail" name="subscriberEmail" placeholder="Email">

CodePudding user response:

The req.body searches for the name attribute in your form. Add the name attribute and then access them via req.body.theNameOfTheAttribute

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

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

  • Related