How to send POST requests with array properties (Ionic 2 HTTP plugin)?

In one of my Ionic 2 projects, I need to send a POST request to a server with a JSON body that looks like this:

var body = { "prop" : 1, 
  "prop2" : "Test", 
  "prop3": [{ "id" : "1", "qty": 1, "details": "Test" }] 
}

      

I am using the following code to call a server using a native HTTP plugin (1.2.0) in Android:

http.post(url, body, {}).then(function() { ... })

      

But my server is getting this:

{ "prop" : 1, 
  "prop2" : "Test", 
  "prop3": "[{ \"id\" : \"1\", \"qty\": 1, \"details\": \"Test\" }]"
}

      

As you can see, the "prop3" array property is converted to a string, so my server doesn't parse it because it expects an array, not a string.

One of the things I can do is change the server side code to parse this string back into an array (but that would be far from ideal). Another thing I could do is parse the JSON object manually using JSON.stringify.

So, is this just a bug in the plugin, or am I missing something here?

Built-in HTTP Plugin

+3


source to share


2 answers


So, looking at the source code of the plugin (Java I, I am testing my app on Android), it seems that I will not be able to use the plugin as is (I will need to change it). I found the following:

In CordovaHttpPost.java, the request body is submitted as form data (simple key values).

request.form(this.getParams());  //Map<?, ?>

      



This is why my array property is being converted to a string (and any other complex object for that matter)

TL; DR this plugin is only useful for sending simple JSON key objects (no nesting, no complex objects, no arrays, etc.).

+1


source


Try to install http.setDataSerializer("json");

AND send data as usual:http.post(url, body, {})



Then the http plugin will send data with content type application / json and support deep json structure as stated in the documentation: https://github.com/silkimen/cordova-plugin-advanced-http#setdataserializer

0


source







All Articles