1

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.

3 Answers 3

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
}));
Sign up to request clarification or add additional context in comments.

2 Comments

A normal HTML form doesn't send JSON.
It is just printing "undefined" in the console now.
0

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

Comments

0

I had this same problem, you need the body parser middleware which can be installed like so

npm i body-parser

Then include it in your server file

const bodyParser = require('body-parser');

And add the following at the top of your server

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

Please note that this module does not handle multipart bodies, due to their complex and typically large nature.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.