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

匿名 (未验证) 提交于 2019-12-03 01:39:01

问题:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!