मैं एक जेसन ऑब्जेक्ट डेटा के साथ सी # से एक POST WebRequest भेजता हूं। और इस तरह एक Node.js सर्वर में इसे प्राप्त करना चाहते हैं:एक्सप्रेस 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');
इसके अलावा, पोस्ट webRequest की सी # अंत के बाद विधि के माध्यम से शुरू हो जाती है
मैं उपरोक्त node.js कोड में अनुरोध ऑब्जेक्ट से JSON डेटा कैसे पार्स कर सकता हूं?
कंसोल में एक महत्वपूर्ण के रूप में अपने वस्तु किक .log (req.body) आउटपुट [ऑब्जेक्ट ऑब्जेक्ट]; मैंने req.body.a भी कोशिश की लेकिन यह अनिर्धारित प्रिंट करता है। – zee
मैंने अपना कोड संपादित कर लिया है, आपकी त्रुटि हर दूसरे मिडलवेयर (बॉडी पार्सर समेत) से पहले राउटर डाल रही थी। – alessioalex
हम्म। लेकिन अब console.log (req.body); आउटपुट {}! जेसन ऑब्जेक्ट गुणों को ए और बी निकालने के लिए कैसे? – zee