如何接收JSON快递Node.js的POST请求? [英] How to receive JSON in express node.js POST request?

查看:126
本文介绍了如何接收JSON快递Node.js的POST请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从C#发送POST的WebRequest用JSON对象数据一起。并希望得到它在这样的服务器的nod​​e.js:

I send a POST WebRequest from C# along with a json object data. And want to receive it in a node.js server like this:

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

Also, the C# end of POST webRequest is invoked via the following method:

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



方法调用:

Method Invocation:

TestPOSTWebRequest("http://localhost:3000/ReceiveJSON", new TestJSONType { a = 2, b = 3 });  



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

How can I parse JSON data from request object in node.js code above?

推荐答案

请求必须与发送:
内容类型:应用/ JSON的;字符集= UTF- 8

The request has to be sent with: content-type: "application/json; charset=utf-8"

否则bodyParser踢你的对象在另一个对象的关键:)

Otherwise the bodyParser kicks your object as a key in another object :)

这篇关于如何接收JSON快递Node.js的POST请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆