【问题标题】:How to receive JSON in express node.js POST request?如何在 express node.js POST 请求中接收 JSON?
【发布时间】:2012-02-03 07:20:16
【问题描述】:

我从 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 数据?

【问题讨论】:

    标签: c# node.js


    【解决方案1】:

    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 的 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 表示 4+。

    【讨论】:

    • console.log(req.body) 输出 [object object];我也试过 req.body.a 但它打印 undefined。
    • 我已经编辑了我的代码,你的错误是将路由器放在所有其他中间件(包括 bodyParser)之前。
    • 嗯。但现在 console.log(req.body);输出 {}!如何提取json对象属性a&b?
    • 如果你运行我的确切代码一切正常,我什至在本地测试过:)
    • 我有你的确切代码兄弟。我还要向你展示 C# webrequest 吗?尽管它确实显示 {"a":2,"b":3} 正在调试中传递。
    【解决方案2】:

    请求必须通过以下方式发送: 内容类型:“应用程序/json;charset=utf-8”

    否则,bodyParser 会将您的对象作为另一个对象的键踢出:)

    【讨论】:

    • 天哪!我怎么错过了!
    • 先生,您救了我的命
    猜你喜欢
    • 2018-10-04
    • 2011-04-14
    • 2020-07-21
    • 1970-01-01
    • 2015-11-26
    • 2017-11-19
    • 1970-01-01
    • 2016-06-12
    • 2020-06-09
    相关资源
    最近更新 更多