Home > Mobile >  TypeError: Cannot read properties of undefined (reading 'name') when I press the Submit Bu
TypeError: Cannot read properties of undefined (reading 'name') when I press the Submit Bu

Time:01-10

When I click Submit to post the entry on MongoDB, it gives me this error MongoDB is connected to the server as well.

This is my router file

const express = require('express');
const Club  = require('../models/club')
const Router = express.Router();


Router.get('/', (eror,res)=>{
    res.render('index')
})

Router.post('/form', (req,res)=>{
    const name = req.body.name;

   console.log(name);
})

module.exports = Router;

This is my form

<form action="/form" method="post">
<input type="text" name="name" placeholder="Add an Entry">
<input type="submit" value="Submit">
</form>```

I tried everything, but it wont work

CodePudding user response:

We have to add middleware to parse request body. In your case:

Router.use(express.urlencoded({ extended: true }))

CodePudding user response:

Depending on your Express version, you might need to use use the bodyParser middleware before your handlers

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

const app = express();
app.use(bodyParser.urlencoded());
...
  • Related