LEE
LEE

Reputation: 3605

Node JS body-parser get rawBody and body

I'm currently implementing the body parser in a way that is mentioned below

 var rawBodySaver = function (req, res, buf, encoding) {
        if (buf && buf.length) {
            req.rawBody = buf.toString(encoding || 'utf8');
        }
    }
    app.use(bodyParser.urlencoded({ extended: true}))
    app.use(bodyParser.json({ verify: rawBodySaver }));
    app.use(bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
    app.use(bodyParser.raw({ verify: rawBodySaver, type: function () { return true } }));

Previously, it was just app.use(bodyParser.urlencoded({ extended: true})) and I got my data in req.body.

But due to some new requirements I had to use rawBody. Is there any way where I can get data in their respective formats in both rawBody and body

Right now, only either of rawBody or body works. Both don not work together.

Upvotes: 2

Views: 6111

Answers (1)

supersam654
supersam654

Reputation: 3244

While a tad hacky, I liked your idea of using the verify function to store the raw body somewhere. I believe your problem was caused by calling bodyParser.* too many times. It appears that only the last call does anything.

const express = require('express')
const app = express()
const bodyParser = require('body-parser')

function rawBodySaver (req, res, buf, encoding) {
  if (buf && buf.length) {
    req.rawBody = buf.toString(encoding || 'utf8')
  }
}

app.use(bodyParser.urlencoded({
  extended: true,
  verify: rawBodySaver
}))

app.post('/', function (req, res, next) {
  console.log(`rawBody: ${req.rawBody}`)
  console.log(`parsed Body: ${JSON.stringify(req.body)}`)
  res.sendStatus(200)
})

// This is just to test the above code.
const request = require('supertest')
request(app)
.post('/')
.set('Content-Type', 'application/x-www-form-urlencoded')
.send('user=tobi')
.expect(200, () => {})

This prints:

rawBody: user=tobi
parsed Body: {"user":"tobi"}

Upvotes: 9

Related Questions