I have a express API which allows json post requests. However, in my scenario, one of my API's needs to accept a XML post body, rather than a JSON one.
So my express app is set fine using:
// Init App
var app = express();
// BodyParser Middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
And here is an example of my POST api JSON route:
router.post('/', function(req, res, next) {
defaultPoll.create(req.body, function(err, post) {
if (err) { console.log(err)
} else {res.json(post);
}
});
});
Which works great when I pass in my json values e.g. this is my Post request:
{
"milliseconds":"600"
}
But now I have an API where I want to do a POST request, but my POST request needs to be send of as XML. So this is what my API looks like:
router.post('/test', function(req, res) {
var body = req
console.log(body)
});
Nothing complicated as im not getting anything back. This is how I do the POST request:
<?xml version="1.0"?>
<methodCall>
<methodName>myMethod</methodName>
<params>
<param>
<value><string>hello</string></value>
</param>
</params>
</methodCall>
However, my body comes back empty. Any idea how I can fix this? Ideally, I would like to take this XML request, and then respond with an XML of my choice too. What is the best way to do this?
Take the request, convert into JSON, write JSON response and convert back to a XML response?
Any help will be appreciated!
The same resource may return either XML or JSON depending upon the request, but it shouldn't return both at the same time.
Data types that REST API can return are as follows: JSON (JavaScript Object Notation) XML.
Using express.json() express. json() is a built in middleware function in Express starting from v4. 16.0. It parses incoming JSON requests and puts the parsed data in req. body .
I know it's lot late but, If you want to use both xml and json, you can use it with specific xml request like this,
app.post('/receive-xml', xmlparser({trim: false, explicitArray: false}), function(req, res, next) {
// check req.body
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With