问题
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 the server using the native HTTP plugin (1.2.0) in Android:
http.post(url, body, {}).then(function() { ... })
But my server is receiving the following:
{ "prop" : 1,
"prop2" : "Test",
"prop3": "[{ \"id\" : \"1\", \"qty\": 1, \"details\": \"Test\" }]"
}
As you can see, the array property "prop3" is being turned into a string, so my server is failing to parse it because it's expecting an array, not a string.
One of the things I could do is to change the server side code to parse this string back into an array (but that would be far from ideal). The other thing I could do is to parse the JSON object manually with JSON.stringify.
So, is this just a bug in the plugin or am I missing something here?
Native HTTP plugin
回答1:
So, after taking a look at the plugin's source code (the Java one, I'm testing my application in Android) it seems that I won't be able to use the plugin as is (I would need to modify it). What I found was this:
In CordovaHttpPost.java, the body of the request is sent as Form data (simple key-values).
request.form(this.getParams()); //Map<?, ?>
That's why my array property is converted into a string (and any other complex object for that matter)
TL;DR this plugin is only useful to send simple JSON key-value objects (no nesting, no complex objects, no arrays, etc.).
回答2:
Try set http.setDataSerializer("json");
And send data as usual: http.post(url, body, {})
Then http plugin will send data with application/json content type and support deep structure of json, as stated in the documentation: https://github.com/silkimen/cordova-plugin-advanced-http#setdataserializer
来源:https://stackoverflow.com/questions/43007794/how-to-send-post-requests-with-array-properties-ionic-2-http-plugin