Home > Net >  Parse XML body from HTTP Push request with Express & Node.js, using body-parser-xml
Parse XML body from HTTP Push request with Express & Node.js, using body-parser-xml

Time:07-10

I need to process a HTTP push request using Node.js express.

The request is sending the body in XML format, that's why I chose the body-parser-xml package for parsing.

My problem is, that the body isn't properly parsed – I guess because the package doesn't recognize the mime type of the transferred body.

The endpoint:

const express = require('express');
const bodyParser = require('body-parser');
require('body-parser-xml')(bodyParser);

const app = express();
const PORT = 8085;

app.use(express.urlencoded({ extended: true }));
app.use(bodyParser.xml({
    limit:'25MB'
}));

app.post('/feed', function (req, res, body) {
    console.log(req.headers);
    console.log(req.body);
    res.status(200).end();
});

The output:

{
  host: 'localhost:8085',
  accept: '*/*',
  'x-meta-feed-type': '1',
  'x-meta-feed-parameters': 'feed params',
  'x-meta-default-filename': 'filename.xml',
  'x-meta-mime-type': 'text/xml',
  'content-length': '63'
  encoding: 'UTF-8',
  connection: 'Keep-Alive'
}
{
  '<data id': '"1234"><name>Test</name><title>Test1234</title></data>'
}

I'm not able to change the request itself (it's external), only the Node.js endpoint.

Any idea how to process the content properly?

Thanks for your help!

CodePudding user response:

The request has apparently been parsed by the

app.use(express.urlencoded({ extended: true }));

middleware, which means that it must have had Content-Type: application/x-www-form-urlencoded. Remove the two app.use lines, because they make "global" body-parsing decisions (for every request), whereas you need a special treatment only for one type of request.

If you instantiate the XML body parser with the "non-standard" (that is, wrong) type, it will parse the content as XML:

app.post('/feed',
  bodyParser.xml({type: "application/x-www-form-urlencoded"}),
  function (req, res) {
    console.log(req.headers);
    console.log(req.body);
    res.status(200).end();
  });
  • Related