2012-01-05 17 views
17

私はjsonオブジェクトデータと共にC#からPOST WebRequestを送信します。そして、このような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)

を行い、あなたのために自動的にそれを行う:あなたが最初bodyParser前app.router()、および他のすべてが含まれているため、コードが間違っています。それは良くないね。 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'); 

あなたはそれらのparamsとPOSTリクエストを送信することにより、Mikealの素敵なRequestモジュールを使用してこれをテストすることができます:

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); 
}); 

更新:ここでは、コードは次のようになります方法です特急4用body-parserを使用+。 コンテンツタイプ:

+0

コンソールでキーとして、オブジェクトをキック.log(req.body)は[オブジェクトオブジェクト]を出力します。私もreq.body.aを試しましたが、定義されていません。 – zee

+0

自分のコードを編集しました。あなたのエラーは、他のすべてのミドルウェア(bodyParserを含む)の前にルータを置いていました。 – alessioalex

+0

hmmm。しかし今はconsole.log(req.body);出力{}! jsonオブジェクトのプロパティを抽出する方法a&b? – zee

27

要求と共に送信されなければならない "アプリケーション/ JSON;のcharset = UTF-8"

そうでない場合bodyParserは、別のオブジェクト:)

+1

oh天才!どのように私はそれを逃した! –

+1

先生、あなたは私の一日を救った – MetaLik

関連する問題