zoecarver
zoecarver

Reputation: 6423

req.body is undefined - nodejs

Here is my html:

<form action='/new'  method='POST' >
  <span>pool name: </span>
  <input type="text" name="name" />
  <input type="hidden" name="imageSrcList" />
  <button type='submit' >Create new</button>
</form>

And here is the relevant JS:

var app = express()
app.use(fileUpload());
app.set('view engine', 'ejs')
app.use(express.static(__dirname + '/views'));

app.post('/new', (req, res) => {
    console.log(req.body.name);
  })

The console reads out:

TypeError: Cannot read property 'name' of undefined

I have tried with console.log(req.body) and this also is undefined.

Thanks in advance!

Upvotes: 1

Views: 2694

Answers (1)

peteb
peteb

Reputation: 19428

You're missing the body-parser middleware which is necessary to have req.body set to a value. Express doesn't come with this by default and will need to be installed via NPM npm i --save body-parser

const bodyParser = require('body-parser')
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))

Upvotes: 8

Related Questions