Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Express API JSON and XML POST request

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!

like image 294
noDe1 Avatar asked Jan 09 '17 16:01

noDe1


People also ask

Does the restful method support JSON or XML or both format?

The same resource may return either XML or JSON depending upon the request, but it shouldn't return both at the same time.

Can I send XML in REST API?

Data types that REST API can return are as follows: JSON (JavaScript Object Notation) XML.

What is app use Express JSON ()) in Express?

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 .


1 Answers

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  
});
like image 130
lazzy_ms Avatar answered Oct 10 '22 22:10

lazzy_ms