Reading html form input with with node.js and express.js

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.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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
}));

Method 2

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())


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x