我從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數據?
控制檯的一個關鍵.log(req.body)輸出[object object];我也嘗試過req.body.a,但它打印未定義。 – zee 2012-01-05 13:27:37
我編輯了我的代碼,你的錯誤是將路由器放在每個其他中間件(包括bodyParser)之前。 – alessioalex 2012-01-05 13:36:03
嗯。但現在console.log(req.body);輸出{}!如何提取json對象屬性a&b? – zee 2012-01-05 13:45:25