Created
January 16, 2017 22:17
-
-
Save macedigital/3799eec3c25a29692a25ee021457b171 to your computer and use it in GitHub Desktop.
Alternative for parsing incoming XML in express apps, instead of using https://github.com/macedigital/express-xml-bodyparser.
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'), | |
typeis = require('type-is'); | |
var app = express(); | |
var xmlParseOptions = { | |
async: false, // Setting to `true` causes issues with exceptions | |
explicitArray: false, | |
trim: true, | |
normalize: true, | |
normalizeTags: true, | |
mergeAttrs: true, | |
charkey: 'value', | |
attrNameProcessors: [function(attr) { | |
return '@' + attr; | |
}] | |
}; | |
app.use(bodyParser.text({ | |
type: '*/xml', | |
limit: '1MB' | |
})); | |
app.use(function(req, res, next) { | |
if(!typeis.hasBody(req) || !typeis(req, '*.xml')) { | |
return next(); | |
} | |
// Parse as XML | |
var parser = new xml2js.Parser(xmlParseOptions); | |
parser.parseString(req.body, function(err, xml) { | |
if(err) { | |
err.status = 400; | |
return next(err); | |
} | |
req.body = xml || req.body; | |
next(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I tried it...
Im only a beginner but i cant get it to work...