首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在快速node.js POST请求中接收JSON?

如何在快速node.js POST请求中接收JSON?
EN

Stack Overflow用户
提问于 2012-01-05 21:05:08
回答 1查看 49.9K关注 0票数 20

我从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# end通过以下方法调用:

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代码中解析request对象中的JSON数据?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8742982

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档