1

I would like to get the raw request body in one of my middlewares in my Express app. There are a few posts on Stackoverflow that show how to do this (e.g. Node.js - get raw request body using Express or Writing express middleware to get raw request body before body-parser), but:

  • They use body-parser, which I believe is built-in with the new Express version, so am not sure how to use it in this case
  • They extract the raw request in app.use(), which means that all routes would extract the raw request, whereas I only want to extract it in one route (more specifically, in an independent middleware that's buried deep in my code rather than in app.js, to which I want to be able to just pass the req element and extract its raw body there).

Any advice on the best way to do this?

KabG
  • 25
  • 6

1 Answers1

0

Assuming you have not already parsed the body before reaching this route (using body-parser or something similar), following will work in your routes file:

var express = require('express');
var router = express.Router();
var bodyParser = require('body-parser');

router.get('/path', bodyParser.raw(options), (req,res){
   //your code
});

bodyParser.raw(options) will return a function that accepts 3 arguments (req,res,next) and the raw body will become available in req.body


s_a94248
  • 148
  • 7
  • Nice, thank you @singh_arpit, that's exactly what I'm looking for. Do I still have to include `var bodyParser = require('body-parser');` with the newer versions of express? – KabG Mar 18 '19 at 14:59
  • I could not confirm that body parser is included as an API of the latest expressJS version. As per this https://expressjs.com/en/4x/api.html#req.body, you have to include it. – s_a94248 Mar 18 '19 at 18:40
  • Thanks! One last question: how do I know whether I've already parsed the body or not? – KabG Mar 18 '19 at 19:26
  • req.body is by default undefined. If it is not, it means body-parser did its work – s_a94248 Mar 19 '19 at 06:14