Reputation: 383
I'm quite new to Swagger, node and express and now facing a little Problem with XML content in POST requests.
I created a project with swagger project create
and selecting express as the framework.
Here is (the interesting part) of my endpoint description I've put in the api/swagger/swagger.yaml
:
[...]
consumes:
- application/xml
- application/json
produces:
- application/json
[...]
paths:
/test:
x-swagger-router-controller: testctrl
post:
description: |
The endpoint that actually consumes the XML data.
parameters:
- name: data
in: body
description: The actual data
required: true
schema:
$ref: "#/definitions/MyData"
responses:
"200":
description: Success
schema:
type: string
In my api/controller/test.js , I have following function:
module.exports = {
post: testctrl_post
};
function testctrl_post(req, res) {
console.log("Received POST request...");
console.log(req.body);
// Here I want to do something with XML data.
res.status(200).json("OK");
}
My problem is, that as soon as I send non-JSON content to the endpoint, the req.body is empty. When I send a JSON like { "test": "test" }
, I can see it in body again.
My question is now, how can I get at least the raw body data to process it with some xml module?
Upvotes: 0
Views: 791
Reputation: 383
Adding the express-xml-bodyparser module by executing:
npm install express-xml-bodyparser
and changing app.js to include the xml parser as follows:
'use strict';
var SwaggerExpress = require('swagger-express-mw');
var express = require('express');
var app = express();
var xmlparser = require('express-xml-bodyparser');
module.exports = app; // for testing
var config = {
appRoot: __dirname // required config
};
app.use(express.json());
app.use(express.urlencoded());
app.use(xmlparser());
SwaggerExpress.create(config, function(err, swaggerExpress) {
if (err) { throw err; }
// install middleware
swaggerExpress.register(app);
var port = process.env.PORT || 10010;
app.listen(port);
if (swaggerExpress.runner.swagger.paths['/hello']) {
console.log('try this:\ncurl http://127.0.0.1:' + port + '/hello?name=Scott');
}
});
The stuff works now.
Upvotes: 1