-2

I am trying to receive an input from an html form in my js file.

HTML

<form action='/bmicalc' method="post">
      <input type='text' name='h' placeholder='Height'>
      <input type='text' name='w' placeholder='Weight'>
      <button type='submit' name='sub'>Calculate</button>
</form>

JS

const express=require('express');
const app=express();

app.get('/',function(req,res){
  res.send('<h1>Hello There!<h1>');
});

app.get('/bmicalc',function(req,res){
  res.sendFile(__dirname+'/bmicalc.html');
})

app.post('/bmicalc',function(req,res){
  console.log(req.body.h);
});

app.listen(3000,function(){
  console.log("Started server on port 3000");
})

However I'm always getting the following error:

TypeError: Cannot read property 'h' of undefined

Can someone please help point out the mistake?

prosoitos
  • 6,679
  • 5
  • 27
  • 41
Biwadeep
  • 31
  • 4
  • It seems the `req.body` is `undefined`. So that's why you cannot access the property `h`. – norbitrial Sep 30 '20 at 20:34
  • But I have form tag within the html body tag. So why should it show undefined? – Biwadeep Sep 30 '20 at 20:35
  • Possible duplicate of [How to retrieve POST query parameters?](https://stackoverflow.com/questions/5710358/how-to-retrieve-post-query-parameters) – esqew Sep 30 '20 at 20:41

1 Answers1

1

The Express API reference makes the following statement clear (emphasis mine):

req.body

Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as express.json() or express.urlencoded().

The code sample you posted does not make use of the middlewares the documentation makes reference to. You can leverage app.use() to enable them:

const express=require('express');
const app=express();

app.use(express.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

app.get('/',function(req,res){
  res.send('<h1>Hello There!<h1>');
});

app.get('/bmicalc',function(req,res){
  res.sendFile(__dirname+'/bmicalc.html');
})

app.post('/bmicalc',function(req,res){
  console.log(req.body.h);
});

app.listen(3000,function(){
  console.log("Started server on port 3000");
})
esqew
  • 42,425
  • 27
  • 92
  • 132
  • Thanks really, wasn't aware of this. – Biwadeep Sep 30 '20 at 20:45
  • According to Mark Bonano: Express doesn't have body-parsing anymore More information here: (as of 2020) https://stackoverflow.com/questions/9177049/express-js-req-body-undefined?rq=1 – Johnty Oct 28 '20 at 20:26