Leo Leo - 4 months ago 13
Node.js Question

ExpressJS: Getting parsed and raw body simultaneously

I'm trying to get both parsed body of a

application/x-www-form-urlencoded
post request and the raw body.

I found similar questions around here but non with a working answer.

I tried using
raw-body
but it ignores this kind of conetnet type.

Now I'm trying to use
body-parser
like so:
app.use(bodyParser.urlencoded());
- it correctly populates the
req.body
but the question is how can I get the raw body as well?

Thanks

Answer

It is possible via bodyParser API to get the raw request body utilizing the verify function.

It is invoked before the stream is parsed with the raw body available as its third argument.

Note that it is a buffer, so you need to call toString if you want it as such:

app.use(bodyParser.urlencoded({
  verify: function(req, res, body) {
    req.rawBody = body.toString();
  }
}));
Comments