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!
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,

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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With