2012-01-05 133 views
17

我從C#發送一個POST WebRequest以及一個json對象數據。並希望得到它的服務器的Node.js這樣的:如何在express node.js POST請求中接收JSON?

public string TestPOSTWebRequest(string url,object data) 
{ 
    try 
    { 
     string reponseData = string.Empty; 

     var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest; 
     if (webRequest != null) 
     { 
      webRequest.Method = "POST"; 
      webRequest.ServicePoint.Expect100Continue = false; 
      webRequest.Timeout = 20000; 


      webRequest.ContentType = "application/json; charset=utf-8"; 
      DataContractJsonSerializer ser = new DataContractJsonSerializer(data.GetType()); 
      MemoryStream ms = new MemoryStream(); 
      ser.WriteObject(ms, data); 
      String json = Encoding.UTF8.GetString(ms.ToArray()); 
      StreamWriter writer = new StreamWriter(webRequest.GetRequestStream()); 
      writer.Write(json); 
     } 

     var resp = (HttpWebResponse)webRequest.GetResponse(); 
     Stream resStream = resp.GetResponseStream(); 
     StreamReader reader = new StreamReader(resStream); 
     reponseData = reader.ReadToEnd(); 

     return reponseData; 
    } 
    catch (Exception x) 
    { 
     throw x; 
    } 
} 

方法調用:

TestPOSTWebRequest("http://localhost:3000/ReceiveJSON", new TestJSONType { a = 2, b = 3 }); 

var express = require('express'); 
var app = express.createServer(); 

app.configure(function(){ 
    app.use(express.bodyParser()); 
}); 
app.post('/ReceiveJSON', function(req, res){ 
        //Suppose I sent this data: {"a":2,"b":3} 

           //Now how to extract this data from req here? 

           //console.log("req a:"+req.body.a);//outputs 'undefined' 
        //console.log("req body:"+req.body);//outputs '[object object]' 


    res.send("ok"); 
}); 

app.listen(3000); 
console.log('listening to http://localhost:3000');  

此外,POST的WebRequest的C#端通過下面的方法調用

如何從上面的node.js代碼中的請求對象解析JSON數據?

回答

22

bodyParser這是否自動爲您,只是做console.log(req.body)

編輯:您的代碼是錯誤的,因爲你首先包括app.router()時,bodyParser之前和一切。那很糟。你甚至不應該包含app.router(),Express會自動爲你做。這裏是你如何代碼應該是這樣的:

var express = require('express'); 
var app = express.createServer(); 

app.configure(function(){ 
    app.use(express.bodyParser()); 
}); 

app.post('/ReceiveJSON', function(req, res){ 
    console.log(req.body); 
    res.send("ok"); 
}); 

app.listen(3000); 
console.log('listening to http://localhost:3000'); 

可以使用Mikeal真好Request模塊,通過發送與PARAMS POST請求測試:

var request = require('request'); 
request.post({ 
    url: 'http://localhost:3000/ReceiveJSON', 
    headers: { 
    'Content-Type': 'application/json' 
    }, 
    body: JSON.stringify({ 
    a: 1, 
    b: 2, 
    c: 3 
    }) 
}, function(error, response, body){ 
    console.log(body); 
}); 

更新:使用body-parser快遞4 +。

+0

控制檯的一個關鍵.log(req.body)輸出[object object];我也嘗試過req.body.a,但它打印未定義。 – zee 2012-01-05 13:27:37

+0

我編輯了我的代碼,你的錯誤是將路由器放在每個其他中間件(包括bodyParser)之前。 – alessioalex 2012-01-05 13:36:03

+0

嗯。但現在console.log(req.body);輸出{}!如何提取json對象屬性a&b? – zee 2012-01-05 13:45:25

27

該請求必須與被髮送: 內容類型: 「應用/ JSON;字符集= UTF-8」

否則bodyParser踢的對象作爲另一個目的:)

+1

哦天才!我怎麼錯過了! – 2013-02-02 00:27:41

+1

先生,你剛剛救了我的一天 – MetaLik 2013-10-29 06:38:07