3

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

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

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.).

4 Comments

what happen when you use JSON.stringify(body)? did you test that?
It gives a "JSON Error", the post method expects an Object for the "body" parameter.
What is the solution for it? I am facing similar issue.
@BalrajAllam I ended up not modifying the plugin. What I did was just to parse the JSON values (strings) server-side. I know it's an ugly solution, but it was the quickest way.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.