Home > other >  Reading html form input with with node.js and express.js
Reading html form input with with node.js and express.js

Time:03-04

I am trying to read the input from an HTML form and use it in Node.js.

This is my HTML form:

    <form action="/myform" method="POST">
        <input type="text" name="mytext" required />
        <input type="submit" value="Submit" />
    </form>

This is my Node.js code:


app.post('/myform', function(req, res){ 
  console.log(req.body.mytext); //mytext is the name of your input box
});

I am getting this error:

TypeError: Cannot read properties of undefined (reading 'mytext')
   

Please help me out.

CodePudding user response:

Make sure you are parsing the request. For that, add the line below at the top of your server root file:

app.use(express.urlencoded({
  extended: true
}));

CodePudding user response:

You have to used a inbuilt method express.json() for parsing json data. To used this method you need middlewares app.use()

So you have to defined it like below but before defining any routes in main file.

app.use(express.json())

  • Related