0

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!

1
  • Where's the Content-Type header that tells Express the body data is XML? Commented Jul 9, 2022 at 16:15

1 Answer 1

2

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();
  });
Sign up to request clarification or add additional context in comments.

2 Comments

Hi Guys, @Heiko, I am still getting an object instead of the XML. I am calling: console.log('Original headers: ' + req.headers); console.log('Original body: ' + req.body); res.send('respond with a API request: ' + req.body); res.status(200).end();. What I am doing wrong? Original body: [object Object]
Avoid string concatenation (+) with an object like req.body. Instead, console.log("Original body", req.body).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.