Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

POST request body not available in Express middleware 'req'

I have an odd query that has really stumped me.

I have created this Express middleware:

const express = require('express')
const bodyParser = require('body-parser')
var router = express.Router()
router.use(bodyParser.urlencoded({ extended: false }))
router.use(bodyParser.json())
app.use(router)

router.use((req, res, next) => {
  console.log(req.body)
})

router.post((req, res) => {
  ...
})

Whever I try to log the body in the router.post, it logs the correct body. However, when I try to log it in the router.use (as shown above), it only returns an empty object. Any thoughts of how I can get the body in middleware? Thanks!

like image 392
Flight Dude Avatar asked Dec 20 '25 20:12

Flight Dude


1 Answers

Only isssue I see according to the official documentation is that you've to set the router to the app after declaring all the middlewares as said in the below attached image,

enter image description here

which means you code should be changed to

const express = require('express')
const bodyParser = require('body-parser')
var router = express.Router()
router.use(bodyParser.urlencoded({ extended: false }))
router.use(bodyParser.json())

router.use((req, res, next) => {
  console.log(req.body)
})

router.post((req, res) => {
  ...
})

//setting the router as a middleware after declaring all the routes and middleware functions.
app.use(router)

References:

  1. Express Routing
  2. Express Router API
like image 169
Lalit Fauzdar Avatar answered Dec 23 '25 12:12

Lalit Fauzdar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!