2015-07-21 94 views
1

我使用Express路由器和Multer中间件来处理多个正文数据和文件,并使用NODEjs构建REST API。POST请求通过requestJS发送JSON对象和图像文件数组

我的端点路径127.0.0.1/api/postData期望:带有字段的json数据,其中之一是json对象数组(我有嵌套猫鼬模式)和2个命名图像(png/jpg)。

我需要通过卷曲发送请求后与以下5个对象的数据结构:

name String 
description String 
usersArray Array of json objects like: [{"id": "123"}, {"id": "456}] 
imgIcon Png/Image providing /path/to/imageIcon.png 
imgHeader Png/Image  providing /path/to/imageHeader.png 

不知道如何编写一个带request.js节点HTTP请求库的帮助这个要求吗?

回答

3

尝试以下操作:

request.post({ 
    url:'http://127.0.0.1:7777/api/postData' 
    , formData: formData 
    , qsStringifyOptions : { 
     arrayFormat : 'brackets' // [indices(default)|brackets|repeat] 
    } 
}, function (err, httpResponse, body) { 
// do something... 
} 

https://www.npmjs.com/package/qs(由https://www.npmjs.com/package/request使用)发现三个选项arrayFormat:

'indices' sends in postbody: (this is the default case) 
usersArray%5B0%5D%5Bid%5D=a667cc8f&usersArray%5B1%5D%5Bid%5D=7c7960fb 
decoded: 
usersArray[0][id]=a667cc8f&usersArray[1][id]=7c7960fb 

'brackets' sends in postbody: 
usersArray%5B%5D%5Bid%5D=a667cc8f&usersArray%5B%5D%5Bid%5D=7c7960fb 
decoded: 
usersArray[][id]=a667cc8f&usersArray[][id]=7c7960fb 

'repeat' sends in postbody: 
usersArray%5Bid%5D=a667cc8f&usersArray%5Bid%5D=7c7960fb 
decoded: 
usersArray[id]=a667cc8f&usersArray[id]=7c7960fb 

这三种不同的方式,在发布前序列化阵列。基本上它取决于接收端如何这些需要/可以格式化。在我的情况下,它有助于使用'括号'

+0

谢谢你HerrZatacke,它帮助! – JavaJedi