如何使用数组属性发送POST请求(Ionic 2 HTTP插件)? [英] How to send POST requests with array properties (Ionic 2 HTTP plugin)?

查看:124
本文介绍了如何使用数组属性发送POST请求(Ionic 2 HTTP插件)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的一个Ionic 2项目中,我需要向服务器发送POST请求,其中JSON正文如下所示:

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" }] 
}

我使用以下代码调用服务器使用Android中的本机HTTP插件(1.2.0):

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\" }]"
}

如您所见,数组属性prop3正在变成一个字符串,所以我的服务器无法解析它,因为它期望一个数组,而不是一个字符串。

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.

我能做的一件事就是改变服务器端代码将此字符串解析回一个数组(但这远非理想)。我能做的另一件事是用JSON.stringify手动解析JSON对象。

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?

原生HTTP插件

推荐答案

所以,看了一下插件的源代码(Java一,我)我正在Android中测试我的应用程序,似乎我无法按原样使用该插件(我需要修改它)。我发现的是:

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:

在CordovaHttpPost.java中,请求的主体作为表单数据(简单键值)发送。

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此插件仅用于发送简单的JSON键值对象(没有嵌套,没有复杂的对象,没有数组等)。

TL;DR this plugin is only useful to send simple JSON key-value objects (no nesting, no complex objects, no arrays, etc.).

这篇关于如何使用数组属性发送POST请求(Ionic 2 HTTP插件)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆