node.js 解析请求的 JSON [英] node.js parse JSON of request

查看:21
本文介绍了node.js 解析请求的 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am sending a credentials JSON object with the following request to node.js:

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

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

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

On the server side i would like to load the submitted credentials into a JSON object to use it further on..

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

However, I don't know how to get the JSON out of the req object...

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

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

(i have a dispatcher in my function(req, res) passing the req further on to controllers, so i would not like to use the .on('data', ...) function)

推荐答案

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

At the server side you will receive the jQuery data as request parameters, not JSON. If you send data in JSON format, you will receive JSON and will need to parse it. Something like:

$.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 数据,请查看此处:如何在 Node.js 中提取 POST 数据?

Note that this will work with GET. To get the POST data, take a look here: How do you extract POST data in Node.js?

要将您的对象序列化为 JSON 并在 jsonData 中设置值,您可以使用 JSON.stringify(credentials)(在最新浏览器中)或 JSON-js.此处示例:在 jQuery 中序列化为 JSON

To serialize your object to JSON and set the value in jsonData, you can use JSON.stringify(credentials) (in newest browsers) or JSON-js. Examples here: Serializing to JSON in jQuery

这篇关于node.js 解析请求的 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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