2016-02-26 34 views
1

我想通過POST應用程序的郵遞員發送一個JSON對象。如何通過郵遞員將JSON發送到NodeJS Express Server?

如果我設置的標題爲'Content-Type: text/plain',然後在另一側上的輸出是一個空對象:

{} 

如果我設置的標題爲Content-Type: application/json,收到以下的響應...

'Error: invalid json'.

的鍵被設置爲ingredients並且該值被設置爲:

{ ["name" : "num1", "quantity" : "5"], ["name" : "num2", "quantity" : "2"], [ "name" : "num3", "quantity" : "8"]} 

我在這裏看到:

router.post('/add', jsonParser, function(req, res) { 

    if (!req.body) return res.sendStatus(400);  
    console.log(req.body); 
}); 
+0

你能詳細說說什麼是jsonParser嗎?它是否像'var jsonParser = bodyParser.json()'? –

回答

1

First of all You need to design data as per your Model . Use http://jsoneditoronline.org/ to format Json with out Syntax errors

Step 1:- Set Url parameters (if you have)

Step 2:- Set Standard Http headers

Example:- 1). Content-Type: application/json 2). Accept : application/json

Then Use http CRUD operations as per Your Requirement

You need to send Data to POST and PUT Actions Get - can get the json from api

Post Ex:- Select Post with API you see 3 options form-data x-www-form-urlencoded raw Select Option "raw" and Paste your Json content

祝您好運! !

+0

謝謝,它現在正在工作 – MikeO

+0

做你的理解好友快樂學習更多的研究! – Prasad

3

您的JSON無效。重構到既能正確解析又能繼續工作的東西。下面的例子應該能正常運行,你的對象數組存儲在ingredients ...

{ 
    "ingredients": [{ 
     "name": "num1", 
     "quantity": "5" 
    }, { 
     "name": "num2", 
     "quantity": "2" 
    }, { 
     "name": "num3", 
     "quantity": "8" 
    }] 
} 

您可以切換這件事,只要你喜歡,只要保證它解析。 JSONLint將是你的朋友。即使沒有一個名爲標識的普通數組也能發揮作用,而更多的我看着它,它看起來好像你只是有你{}[]語法向後...

[{"name": "num1", "quantity": "5"}, {"name": "num2","quantity": "2"}, {"name": "num3","quantity": "8"}] 
+0

這不起作用 {「ingredients」:[{「name」:「num1」,「quantity」:「5」},{「name」:「num2」,「quantity」:「2」}, {「name」:「num3」,「quantity」:「8」}]} – MikeO

+0

感謝您的幫助 – MikeO

+0

我給了你原始的json對象。這是根本問題,不是如何與郵遞員即插即用。無論哪種方式,我看到你想出了它 – scniro

相關問題