Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Extract request body information using app.use(req) – NodeJS Express

I am working on a NodeJS API and I have the below folder structure. I need to extract the request body information of an API call from the index.js itself before passing it to the stripeController.js.

  • index.js
    • Controllers
      • stripeController.js

I am using the below code segment for data extraction from index.js however it returns undefined as it cannot identify req.body at the time the request goes through the index.js.

app.use((req, res, next) => {
  if (req.originalUrl.startsWith('/api/stripeWebHook')) {
    console.log(req.body)
    next();
  }
});

const stripeWebHook = require('./webhook/stripeWebHook')
app.use('/api/stripeWebHook', stripeWebHook)

module.exports = app

I can simply extract the body when it reaches the stripeController.js using the same attribute.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I resolve this?

>Solution :

req.body
Contains key-value pairs of data submitted in the request body. By default, it is undefined, and is populated when you use body-parsing middleware such as body-parser or multer.

const app = require('express')()
const bodyParser = require('body-parser')
const multer = require('multer') // v1.0.5
const upload = multer() // for parsing multipart/form-data

app.use(bodyParser.json()) // for parsing application/json
app.use(bodyParser.urlencoded({ extended: true })) // for parsing application/x-www-form-urlencoded

app.post('/', (req, res, next) => {
  res.json(req.body)
})
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading