cURL后JSON数据,JSON数组和图像文件REST API测试

问题描述:

我正面临着通过cURL复杂的http请求的问题。 我正在用NODEjs构建REST API,使用Express路由器和Multer中间件来处理多个身体数据和文件。cURL后JSON数据,JSON数组和图像文件REST API测试

我的端点路由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 

我读过很多关于计算器线程的,但所有的人都回答特定问题奇异,一个关于卷曲后期图像的主题,另一个cURL后期数组,但不完全。

我已经试过REST API测试工具,如邮递员,DHC(谷歌浏览器),并有一切都很好,除了arraysArray场 我使用的领域,如:
usersArray [0] {“ID”:“123” } usersArray [1] {“id”:“456”}
但验证没有通过,因为json对象的值被不正确的解析。

所以我决定把所有内容放在cURL脚本中。

我试着写我在下面的方式卷曲的要求:

#!/bin/bash 
    curl -H 'Content-Type: application/json' 
    -H 'Accept: application/json' -X POST 
-F "name=Foo Name Test" 
--data '[{"id": "a667cc8f-42cf-438a-b9d8-7515438a9ac1"}, {"id": "7c7960fb-eeb9-4cbf-9838-bcb6bc9a3878"}]' 
-F "description=Super Bar" 
-F "[email protected]/home/username/Pictures/imgIcon.png" 
-F "[email protected]/home/username/Pictures/imgHeader.png" http://127.0.0.1:7777/api/postData 

当我在bash 运行我的脚本cUrl作者./postData

我得到这个: $警告:您只能选择一个HTTP请求!

你可以帮助:

1)任何想法如何在卷曲

2)或工具(如DHC,邮差建议写这样一个复杂的HTTP REST请求)来解决这个复杂的HTTP请求。

3)或者与任何想法如何写request.js节点http请求库的帮助下写这个请求。

非常感谢大家对所有的答案,想法和想法!

问候,JJ

您可以尝试邮差或Google Chrome分机应用的REST API测试DHC。 但是,您应该使用多维数组而不是将JSON对象用作值,这可能会在验证期间导致问题。

在DHC尝试这种情况:

|FIELD|   |VALUE| 
name    'Some name' 
description  'Some description' 
usersArray[0][id] 89a7df9 
usersArray[1][id] dskf28f 
imgIcon   (select type of field "file" and upload image) 
imgHeader   (select type of field "file" and upload image) 

它工作以上的方式是: usersArray [0] [ID]指定多维数组和与键 “ID” 位置0的对象{}的地方和值你可以在价值部分中选择。usersArray [1] [id]“456”将另一个元素添加到数组,因此数组变成:[{“id “:”123“},{”id“:”456“}]

+0

酷,在DHC完美工作!从现在开始,我将使用DHC处理这种复杂的http请求情况。 – JavaJedi

有时你会想使用shell + curl来创建RestAPI调用,并且你可能想要传递复杂的json作为数据。如果你想在执行期间使用变量并创建这些数据,你最终可能会使用很多转义字符(),并且代码看起来很丑。我也在做同样的事情,Windows PowerShell有一种方法将Dictionary | Associative Array转换为JSON,这在该领域确实有所帮助,但寻找类似的东西但找不到任何东西。所以这是一个示例代码,将有助于:

#!/bin/Bash 
# Author [email protected] 

## Variable Declaration 
email="[email protected]" 
password="VerySecurePassword" 
department="Department X" 

## Create JSON using variables in Bash 
creds="{^email^:^${email}^, ^password^:^${password}^}" 
department="{^department^:^${department}^}" 
authdata_crippled="{^Authenticate^:[${creds},${department}]}" 
# Replace^with " 
authdata_json_for_RestAPI_Call=$(echo ${authdata_crippled}|tr '^' '"') 

# Testing syntax 
# Get "jq": yum install jq OR https://stedolan.github.io/jq/ 
echo ${authdata_json_for_RestAPI_Call} | jq . 

# Then you make API call using curl 
# Eg: 
curl http://hostname:port/right/endpoint/for/api/Authenticate -X POST --header "Content-Type:application/json" -d ${authdata_json_for_RestAPI_Call} --cookie-jar cookie.data 

希望这可以帮助别人。