2012-01-05 22 views
17

Invio una POST WebRequest da C# insieme a dati di oggetti json. E vogliono riceverlo in un server node.js come questo:Come ricevere JSON in express node.js Richiesta POST?

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

Inoltre, l'estremità C# di POST webRequest viene richiamato tramite il seguente metodo:

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

Method Invocation:

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

Come posso analizzare i dati JSON dall'oggetto richiesta nel codice node.js sopra?

risposta

22

bodyParser lo fa automaticamente per voi, basta fare console.log(req.body)

Edit: il codice è sbagliato, perché si include prima app.router(), prima che il bodyParser e tutto il resto. Questo è male. Non dovresti nemmeno includere app.router(), Express lo fa automaticamente per te. Ecco come il codice dovrebbe essere simile:

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

È possibile verificare ciò utilizzando bel modulo di Mikeal Request, con l'invio di una richiesta POST con quegli params:

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

Aggiornamento: utilizzare body-parser per Express 4 +.

+0

console .log (req.body) restituisce [oggetto oggetto]; Ho provato anche req.body.a ma stampa indefinito. – zee

+0

Ho modificato il mio codice, il tuo errore stava mettendo il router prima di ogni altro middleware (incluso bodyParser). – alessioalex

+0

hmmm. ma ora console.log (req.body); uscite {}! come estrarre le proprietà dell'oggetto json a & b? – zee

27

La richiesta deve essere inviato con: Content-Type: "application/json; charset = utf-8"

Altrimenti il ​​bodyParser calci l'oggetto come una chiave in un altro oggetto :)

+1

oh genio! come mi è mancato! –

+1

signore, hai appena salvato la mia giornata – MetaLik

Problemi correlati