How to use `bodyParser.raw()` to get raw body? How to use `bodyParser.raw()` to get raw body? express express

How to use `bodyParser.raw()` to get raw body?


if you want to send a raw data and get with body parser you just configure this way:

app.use(bodyParser.raw({ inflate: true, limit: '100kb', type: 'text/xml' }));

That behavior doesn't corrupt the body content.


The parsed body should be set on req.body.

Keep in mind that middleware is applied in the order you set it with app.use, my understanding is that applying the bodyParser multiple times as you have will attempt to parse the body in that order, leaving you with the result of the last middleware to operate on req.body, i.e. since both bodyParser.json() and bodyParser.raw() both accept any inputs, you will actually end up attempting to parse everything from a Buffer into JSON.


To parse all content types I use:

app.use(  express.raw({    inflate: true,    limit: '50mb',    type: () => true, // this matches all content types  }));

To get the raw body in just a single route:

app.put('/upload', express.raw({ inflate: true, limit: '50mb', type: () => true }), async (req, res) => {  res.json({ bodySize: req.body.length });});

In that case note that the previously app.use()'d body parsers (json for example) are executed first - so check that req.body is indeed a Buffer, otherwise a malicious caller could send something like {"length":9999999} with Content-Type: application/json.