Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
like image 469
Believe2014 Avatar asked Jul 19 '16 21:07

Believe2014


1 Answers

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.

like image 194
Moritz Avatar answered Oct 12 '22 18:10

Moritz