Not able to take inputs from HTML form with Node Js

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("https://stackoverflow.com/",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");
})

Leave a Comment