2015-07-20 18 views
0

我正面臨着通過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

回答

0

您可以嘗試郵差或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

0

有時你會想使用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 

希望這可以幫助別人。