Ответ 1
Запрос должен быть отправлен с: content-type: "application/json; charset = utf-8"
В противном случае bodyParser ударяет ваш объект в виде ключа в другом объекте:)
Я отправляю POST WebRequest из С# вместе с данными объекта json. И хотите получить его на сервере node.js следующим образом:
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 вызывается с помощью следующего метода:
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 });
Как я могу проанализировать данные JSON из объекта запроса в node.js выше?
Запрос должен быть отправлен с: content-type: "application/json; charset = utf-8"
В противном случае bodyParser ударяет ваш объект в виде ключа в другом объекте:)
bodyParser делает это автоматически для вас, просто console.log(req.body)
Изменить. Ваш код неверен, потому что вы сначала включаете app.router(), перед bodyParser и все остальное. Это плохо. Вы даже не должны включать 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');
Вы можете проверить это, используя Mikeal nice Request, отправив запрос POST с этими параметрами:
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);
});
Обновить: используйте body-parser для express 4 +.