Skip to content

Instantly share code, notes, and snippets.

@macedigital
Created January 16, 2017 22:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save macedigital/3799eec3c25a29692a25ee021457b171 to your computer and use it in GitHub Desktop.
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.
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();
});
});
@Code-Tap
Copy link

I tried it...
Im only a beginner but i cant get it to work...

var express = require('express'),
    typeis = require('type-is'),
    ip = require('ip'),
    bodyParser = require('body-parser');

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();
  });
});

// XML Response Route
app.post('/', function (req, res) {
    console.log(req.body);
    res.status(200).send(req.body)
})

//.. Run Server
let server = app.listen(3000, function () {
    console.log('API running at', ip.address(),':', server.address().port);
});

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