Andrey Kon Andrey Kon - 1 year ago 84
Node.js Question

Expressjs raw body

How can I access raw body of request object given to me by expressjs?

var express = require('./node_modules/express');
var app = express.createServer();'/', function(req, res)
console.log(req.body); //says 'undefined'


Default express does not buffer data unless you add middleware to do so. The simple solution is to follow the example in @Stewe's answer below, which would just concatenate all of the data yourself. e.g.

var concat = require('concat-stream');
app.use(function(req, res, next){
    req.body = data;

The downside of this is that you have now moved all of the POST body content into RAM as a contiguous chunk, which may not be necessary. The other option, which is worth considering but depends on how much data you need to process in the post body, would be to process the data as a stream instead.

For example, with XML you could use an XML parser that supports parsing XML as it comes in as chunks. One such parser would be XML Stream. You do something like this:

var XmlStream = require('xml-stream');'/', function(req, res) {
  var xml = new XmlStream(req);
  xml.on('updateElement: sometag', function(element) {
    // DO some processing on the tag
  xml.on('end', function() {