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

Believe2014 picture Believe2014 · Jul 19, 2016 · Viewed 19.5k times · Source

I am creating a web API using Express. The feature is to allow API users to send a file to the server.

Here's my app setup code:

var express = require('express');
var path = require('path');
// ...
var bodyParser = require('body-parser');

var routes = require('./routes/index');
var users = require('./routes/users');

// API routes
var images = require('./routes/api/img');

var app = express();

app.use(bodyParser.raw());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', routes);
app.use('/api', images);

// ...

module.exports = app;

Please notice that I am using app.use(bodyParser.raw());.

How do I get the raw bytes from POST requests?

const express = require('express');
const router = express.Router();

/* POST api/img */
router.post('/img', function(req, res, next) {

  // how do I get the raw bytes?

});

module.exports = router;

Answer

joelton picture joelton · Apr 12, 2018

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.