Express: rawBody / buffer on a single route

1.2k Views Asked by At

I need to grab the rawBody (buffer) for a POST request, but I only need to do this on a single route in my application.

Currently, I'm using the following in my main app.js:

app.use(bodyParser.json({ verify: function(req, res, buf) { req.rawBody = buf; }}));

This works, but it is sending the buffer for every route. This is undesirable because it uses twice the RAM for every request in my app.

How can I instead obtain the rawBody on the single route I need it for?

2

There are 2 best solutions below

0
On BEST ANSWER

Typically, you'd create that single route and inline the middleware:

app.post('/route', bodyParser.json(...), function(req, res) {
  ...
});

Followed by the "normal" setup:

app.use(bodyParser.json());

app.post('/another-route', function(req, res) {
  ...
});

Instead of abusing bodyParser.json(), you could also consider using bodyParser.raw().

0
On

If its trivial to refer to the specific route then this would work.This is a very simplistic representation of the idea:

var routeIWantToBuffer = "someroute";
app.use(bodyParser.json(
  {
    verify: function(req, res, buf) { 
      if(req.route === routeIWantToBuffer) req.rawBody = buf;
    }
  }
));

Usually route/use functions also have a next argument which is used to continue the chain. I'm not saying this is wrong, but I don't know what the rest of your code looks like. But I would expect it to look like this:

var routeIWantToBuffer = "someroute";
app.use(bodyParser.json(
  {
    verify: function(req, res, buf, next) { 
      if(req.route === routeIWantToBuffer) req.rawBody = buf;
      next();
    }
  }
));