How to fix "req.body undefined" in Express.js


express.js node

I setup a simple application with Express.js v4.17.1. I had put source code to the index.js file:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.post('/apple', (req, res) => {
    console.log(req.body)
    res.send('Hello World!')
  })

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

I ran this server and when sent POST request (with primitive payload) to the /apple endpoint, I got this output:

r.akhromieiev@MacBook-Pro apple-shortcus % node index.js 
Example app listening at http://localhost:3000
undefined

This output means that req.body is undefined, but it should contain my payload.

Solution

Step 1 : Because we are using Express@4 we need to install body-parser package:

npm i body-parser --save

Step 2 : Then we need to extract it in the index.js:

const bp = require('body-parser')

Step 3 : On this step we had to pass bp.json() and bp.urlencoded({ extended: true }) to the application-level middleware:

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

These methods will parse incoming requests and extract the body.

Step 4 : I restarted the app and now my output contained the payload:

r.akhromieiev@MacBook-Pro apple-shortcus % node index.js 
Example app listening at http://localhost:3000
{ status: 'Ok' }

Source code

const express = require('express')
const bp = require('body-parser')
const app = express()
const port = 3000

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

app.get('/', (req, res) => {
	res.send('Hello World!')
})

app.post('/apple', (req, res) => {
	console.log(req.body)
	res.send('Hello World!')
})

app.listen(port, () => {
	console.log(`Example app listening at http://localhost:${port}`)
})
comments powered by Disqus