2012-01-05 39 views
17

C# 'dan bir POST WebRequest'i bir json nesne verisiyle birlikte gönderiyorum. Ve böyle bir node.js sunucuya bunu almak istiyorum:Express node.js POST isteği içinde JSON nasıl alınır?

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

Yordam Çağırımı:

TestPOSTWebRequest("http://localhost:3000/ReceiveJSON", new TestJSONType { a = 2, b = 3 }); 
Ayrıca
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# ucu aşağıdaki yöntemi ile çağrılır

Yukarıdaki node.js kodundaki JSON verilerini istek nesnesinden nasıl ayrıştırabilirim?

cevap

22

bodyParser sadece Düzenconsole.log(req.body)

yapmak sizin için otomatik bunu yapmaz: İlk bodyParser önce app.router() ve diğer her şeyi içerir çünkü kod yanlıştır. Bu kötü. App.router() 'i bile eklememelisiniz, Express sizin için otomatik olarak yapar.

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

Siz bu parametreleri içeren bir POST isteği göndererek, Mikeal en güzel Request modülü kullanarak test edebilirsiniz:

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

Güncelleme: Burada kod gibi görünmelidir nasıl 4 ekspres için body-parser kullanmak +. içerik tipi:

+0

konsol bir anahtar olarak nesne başladı .log (req.body) çıktılar [object object]; Req.body.a'yı da denedim ama tanımsız basılıyor. – zee

+0

Kodumu düzenledim, hatanız diğer tüm ara yazılımlardan (bodyParser dahil) önce yönlendiriciyi koyuyordu. – alessioalex

+0

hmmm. ama şimdi console.log (req.body); çıktılar {}! json nesne özellikleri a & b nasıl çıkartılır? – zee

27

talebi gönderilir gereken "uygulama/json; charset = UTF-8"

Aksi bodyParser başka bir nesne :)

+1

oh genius'ta gerekli değildir! bunu nasıl özledim! –

+1

efendim, sadece günümü kurtardın – MetaLik