如何在express node.js POST请求中接收JSON?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (2)
  • 关注 (0)
  • 查看 (240)

我从C#发送一个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的C#结尾:

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

我如何从上面的node.js代码中的请求对象中解析JSON数据?

提问于
用户回答回答于
用户回答回答于

该请求必须与以下内容一起发送:content-type:“application / json; charset = utf-8”

扫码关注云+社区