Last Updated: November 09, 2017
·
18.7K
· Pavel Evstigneyev

Capture raw post body in express.js

I tried to use raw-body but it don't work when using together with body-parser.

This worked well:

var bodyParser = require('body-parser');
var rawBodySaver = function (req, res, buf, encoding) {
 if (buf && buf.length) {
 req.rawBody = buf.toString(encoding || 'utf8');
 }
}

app.use(bodyParser.json({ verify: rawBodySaver }));
app.use(bodyParser.urlencoded({ verify: rawBodySaver, extended: true }));
app.use(bodyParser.raw({ verify: rawBodySaver, type: function () { return true } }));

If one of bodyParser middleware apply then next one will not run. If request is not a json nor urlencoded then raw parser will process it.

This not working for long bodies:

app.use(function(req, res, next) {
 var data = '';
 req.on('data', function(chunk) { 
 data += chunk;
 });
 req.on('end', function() {
 req.rawBody = data;
 });
 next();
});