Created
March 31, 2013 14:49
-
-
Save tfanme/5280854 to your computer and use it in GitHub Desktop.
using xml2js to enable request body parsing for express
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var express = require('express'), | |
var app = express(); | |
var utils = require('express/node_modules/connect/lib/utils'), xml2js = require('xml2js'); | |
function xmlBodyParser(req, res, next) { | |
if (req._body) return next(); | |
req.body = req.body || {}; | |
// ignore GET | |
if ('GET' == req.method || 'HEAD' == req.method) return next(); | |
// check Content-Type | |
if ('text/xml' != utils.mime(req)) return next(); | |
// flag as parsed | |
req._body = true; | |
// parse | |
var buf = ''; | |
req.setEncoding('utf8'); | |
req.on('data', function(chunk){ buf += chunk }); | |
req.on('end', function(){ | |
var parseString = xml2js.parseString; | |
parseString(buf, function(err, json) { | |
if (err) { | |
err.status = 400; | |
next(err); | |
} else { | |
req.body = json; | |
next(); | |
} | |
}); | |
}); | |
}; | |
app.configure(function() { | |
app.use(express.logger('dev')); /* 'default', 'short', 'tiny', 'dev' */ | |
app.use(express.bodyParser()); | |
app.use(xmlBodyParser); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment