Skip to content

Instantly share code, notes, and snippets.

@davidkrisch
Created March 26, 2012 23:13
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save davidkrisch/2210498 to your computer and use it in GitHub Desktop.
Save davidkrisch/2210498 to your computer and use it in GitHub Desktop.
Express-Node: Accepting POST with Content-Type: application/xml
// This script requires Express 2.4.2
// It echoes the xml body in the request to the response
//
// Run this script like so:
// curl -v -X POST -H 'Content-Type: application/xml' -d '<hello>world</hello>' http://localhost:3000
var express = require('express'),
app = express.createServer();
express.bodyParser.parse['application/xml'] = function(data) {
return data;
};
app.configure(function() {
app.use(express.bodyParser());
});
app.post('/', function(req, res){
res.contentType('application/xml');
res.send(req.body, 200);
});
app.listen(3000);
@tfanme
Copy link

tfanme commented Mar 26, 2013

"
express.bodyParser.parse['application/xml'] = function(req, options, callback)
^
TypeError: Cannot set property 'application/xml' of undefined
"
under express 3.1.

I wonder how can I fix this problem to extend express's bodyParser?

@tysonnero
Copy link

@princetoad I'm getting the same error.

@donpdonp
Copy link

http://stackoverflow.com/questions/11625519/how-to-access-the-request-body-when-posting-using-node-js-and-express
"Express's bodyParser only parses the incoming data, if the content-type is set to either of the following:

  • application/x-www-form-urlencoded
  • application/json
  • multipart/form-data

In all other cases, it does not even bother reading the data."

this anyBodyParser will always ready the body and put the content into req.rawBody

// Run this script like so:
// curl -v -X POST -H 'Content-Type: application/xml' -d '<hello>world</hello>' http://localhost:3000
var express = require('express'),
    app = express();

function anyBodyParser(req, res, next) {
    var data = '';
    req.setEncoding('utf8');
    req.on('data', function(chunk) { 
        data += chunk;
    });
    req.on('end', function() {
        req.rawBody = data;
        next();
    });
}

app.configure(function() {
  app.use(anyBodyParser);
});


app.post('/', function(req, res){
    console.dir(req.rawBody)
    res.contentType('application/xml');
    res.send(req.body, 200);
});

app.listen(3000);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment