【问题标题】:node.js parse JSON of requestnode.js 解析请求的 JSON
【发布时间】:2012-08-13 06:07:16
【问题描述】:

我正在向 node.js 发送带有以下请求的凭据 JSON 对象:

credentials = new Object();
credentials.username = username;
credentials.password = password;

$.ajax({
    type: 'POST',
    url: 'door.validate',
    data: credentials,
    dataType: 'json',
    complete: function(validationResponse) {
        ...
    }
});

在服务器端,我想将提交的凭据加载到 JSON 对象中以进一步使用它..

但是,我不知道如何从 req 对象中获取 JSON...

http.createServer(
    function (req, res) {
         // How do i acess the JSON
         // credentials object here?
    }
).listen(80);

(我的函数(req, res)中有一个调度程序将 req 进一步传递给控制器​​,所以我不想使用 .on('data', ...) 函数)

【问题讨论】:

    标签: json node.js request


    【解决方案1】:

    Console.log 请求

    http.createServer(
        function (req, res) {
    
        console.log(req); // will output the contents of the req
    
        }
    ).listen(80);
    

    如果发送成功,帖子数据会在某处。

    【讨论】:

    • 谢谢,我打印了,没有数据。你知道为什么吗?
    • 发现了,不得不在 POST ajax 请求中使用 JSON.stringify(credentials)。
    【解决方案2】:

    在服务器端,您将接收 jQuery 数据作为请求参数,而不是 JSON。如果您以 JSON 格式发送数据,您将收到 JSON 并需要对其进行解析。比如:

    $.ajax({
        type: 'GET',
        url: 'door.validate',
        data: {
            jsonData: "{ \"foo\": \"bar\", \"foo2\": 3 }"
            // or jsonData: JSON.stringify(credentials)   (newest browsers only)
        },
        dataType: 'json',
        complete: function(validationResponse) {
            ...
        }
    });
    

    在服务器端你会做:

    var url = require( "url" );
    var queryString = require( "querystring" );
    
    http.createServer(
        function (req, res) {
    
            // parses the request url
            var theUrl = url.parse( req.url );
    
            // gets the query part of the URL and parses it creating an object
            var queryObj = queryString.parse( theUrl.query );
    
            // queryObj will contain the data of the query as an object
            // and jsonData will be a property of it
            // so, using JSON.parse will parse the jsonData to create an object
            var obj = JSON.parse( queryObj.jsonData );
    
            // as the object is created, the live below will print "bar"
            console.log( obj.foo );
    
        }
    ).listen(80);
    

    请注意,这将适用于 GET。要获取 POST 数据,请查看此处:How do you extract POST data in Node.js?

    要将您的对象序列化为 JSON 并在 jsonData 中设置值,您可以使用JSON.stringify(credentials)(在最新的浏览器中)或JSON-js。这里的例子:Serializing to JSON in jQuery

    【讨论】:

    • 请注意,它可能在某些时候在 GET 中工作。如果发送到 GET 方法的序列化数据太大,可能会被截断,导致服务器端的 json 无效。
    猜你喜欢
    • 2019-05-03
    • 2014-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-31
    • 2017-04-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多