express.js 4 GET请求中的JSON解析问题(从数据表请求数据) [英] express.js 4 JSON parsing problems from GET request (request data from datatables)

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

问题描述

我在解析序列化的JSON Ajax Get请求(使用jQuery $ .ajax)发送到我的express.js 4服务器时遇到问题。以JSON请求发送的数据是由数据表生成的。



这是我如何在客户端开始



< pre class =lang-js prettyprint-override> $(document).ready(function(){
$('#example')。dataTable({
bServerSide :true,
fnServerData:function(sSource,aoData,fnCallback){
$ .ajax({
dataType:'json',
contentType:'application / json',
type:GET,
url:http:// localhost:3000 / ajax / phenotypes / withOrg / like / datatables /,
数据:aoData,
success:fnCallback,
error:function(){
alert('have some problem');
}
} );
}
});
});

当我在浏览器中加载此代码时,数据表会生成以下GET请求URL(到服务器):


GET
/ ajax /表型/ withOrg / like / datatables /?draw = 1& columns =%5Bobject + 5D%2C%5B对象+对象%5D%2C%5B对象+对象%5D%2C%5B对象+对象%5D%2C%5B对象+对象%5D%2C%5B对象+对象%5D&顺序=%5B对象+对象%5D& ; start = 0& length = 10& search =%5Bobject + Object%5D


或解码形式(从firebug输出) / p>

  columns [object Object],[object Object],[object Object],[object Object],[object Object] object object] 
draw 1
length 10
order [object Object]
search [object Object]
start 0

所以我发送之前序列化数据

  $(document).ready(function(){
$('#example ').dataTable({
bServerSide:true,
fnServerData:function(sSource,aoData,fnCallback){
var myData = JSON.stringify(aoData);
$ .ajax({
dataType:'json',
contentType:'application / json',
type:GET,
url:http:// localhost:3000 / ajax /表型/ withOrg / like / datatables /,
data:myData,
success:fnCallback,
:function(){
alert('have some problem');
}
});
}
});
});

这里是从数据表生成的GET参数:


GET
/ ajax /表型/ withOrg / like / datatables /?[{%22name%22:%22draw%22,%22value%22:1},{%22name %22:%22列%22,%22value%22:[{%22data%22:0,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22 :{%22value%22:%22%22,%22regex%22:false}},{%22data%22:1,%22name%22:%22%22,%22searchable%22:true,%22orderable%22 :true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{%22data%22:2,%22name%22:%22%22,%22searchable%22 :true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{%22data%22:3,%22name%22:%22 %22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{%22data%22: %22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{ %22数据%22:5,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%2 2%22,%22regex%22:false}}]},{%22name%22:%22order%22,%22value%22:[{%22column%22:0,%22dir%22:%22asc%22} ],{%22name%22:%22start%22,%22value%22:0},{%22name%22:%22length%22,%22value%22:10},{%22name%22:%22search% 22,%22value%22:{%22value%22:%22%22,%22regex%22:false}}]
HTTP / 1.1


解码形式(从firebug输出并使用在线工具进行美化 - 用jslint进行检查,似乎正确!)

  
name:draw,
value:1
},
{
name列,
value:[
{
data:0,
name:,
可搜索:true,
orderable:true,
search:{
value:,
regex:false
}
},
{
data:1,
name:,
可搜索:true,
可订购:true,
search:{
value:,
regex:false
}
},
{
data:2 ,
name:,
可搜索:true,
可订购:true,
search:{
value ,
regex:false
}
},
{
data:3,
name:,
searchable:true,
orderable:true,
search:{
value:,
regex:false

},
{
data:4,
name:,
可搜索:true,
:true,
search:{
value:,
regex:false
}
},
{
data:5,
name:,
可搜索:true,
可订购:true,
search:{
value:,
regex:false
}
}
]
},
{
name:order,
value :[
{
column:0,
dir:asc
}
]
},
{
name:start,
value:0
},
{
name:length,
value :10
},
{
name:search,
value:{
value:,
regex:false
}
}
]

问题是现在这个字符串的URL不能在express 4服务器端解析
我使用express4 req.query和url.parse方法: http://expressjs.com/api.html#req.query
和t母鸡尝试用JSON.parse()方法解析收到的json字符串

  ... 
var url = require('url');
...

router.get('/ withOrg / like / datatables /',function(req,res){
console.log('通过req获取json字符串.query');
console.log(req.query);
console.log('使用JSON.parse输出解析的json对象);
console.log(JSON.parse( req.query));

//另一个尝试
console.log('为堆栈溢出测试2');
console.log(url.parse(req.url ,true).query);
console.log('使用JSON.parse输出解析的json对象);
console.log(url.parse(req.url,true).query);
})

两个json字符串输出结果都是无效的json,你可以在这里看到,无法解析JSON.parse:

 通过req.query获取json字符串
pre>


{
'{data:0,name:,可搜索:true,可靠的:true,可搜索:true,可订购:true ,搜索:{va lue:,regex:false}},{data:2,name:,可搜索:true,orderable:true,search:{value ,regex:false}},{data:3,name:,可搜索:true,orderedable:true,search:{value:,regex :false}},{data:4,name:,可搜索:true,orderable:true,search:{value:,regex },{data:5,name:,searchable:true,orderable:true,search:{value:,regex:false} b $ b {'{column:0,dir:asc}':''}}




 使用JSON.parse输出解析的json对象

通过req.query获取json字符串




{
'{data:0,name:,可搜索:true,orderedable搜索:{value:,regex:false}},{data:1,name:,可搜索:true,orderable value:,regex:false}},{data:2,name:,可搜索:true,orderable:true,search:{value ,regex:false}},{data:3,name:,可搜索:true,orderedable:true,search:{value regex:false}},{data:4,name:,可搜索:true,orderedable:true,search:{value:,regex false}},{data:5,name:,可搜索:true,orderable:true,search:{value:,regex :
{'{column:0,dir:asc}':''}}




< p $ p> 输出解析json对象使用JSON.parse

当我尝试解析json字符串我从JSON.parse中获取错误

  SyntaxError:意外的令牌o 
在Object.parse (native)
在module.exports(/Users/xxx/yyy/routes/phenotypesAJAX.js:16:19)
在Layer.handle [as handle_request](/ Users / xxx / yyy / node_modules /express/lib/router/layer.js:82:5)
在下一个(/Users/xxx/yyy/node_modules/express/lib/router/route.js:100:13)

这是一个在快递4中的错误?
我看不到问题在哪里。在客户端,序列化的datatable GET请求似乎有效(使用JSLint检查)。在express4服务器端,我找不到任何其他方法来解析GET请求。



非常感谢你的帮助,
Oliver

解决方案

我在快速github bugtracker上发布了这个问题的答案。
经验教训:
我正在想复杂,express.js请求方法不是特别为特定的请求格式写的!他们只是使用发送给他们的数据格式,而无需修改!



我先使用的方法:

  req.query 




[。 。]只适用于标准查询字符串,这是key = value对,
,您给的URL不是。[..]


解决我的问题的正确方法是:

  url.parse(req.url).query 

返回不必手动解码的URL的完整参数字符串:

  obj = JSON.parse(decodeURIComponent(query))

这是完整的解释:
https:// github。 com / strongloop / express / issues / 2460


I am having problems parsing a serialized JSON Ajax Get request (using jQuery $.ajax) send to my express.js 4 server. The data send as a JSON request is generated by datatables.

Here is how I started on the client-side

$(document).ready(function() {
    $('#example').dataTable( {
        "bServerSide": true,
        "fnServerData": function (sSource, aoData, fnCallback) {
            $.ajax({
                "dataType": 'json',
                contentType: 'application/json',
                "type": "GET",
                "url": "http://localhost:3000/ajax/phenotypes/withOrg/like/datatables/",
                "data": aoData,
                "success": fnCallback,
                "error": function () {
                    alert('have some problem');
                }
            });
        }                   
    } );
} );

when I load this code in the brower datatables generates the following GET request URL (to the server):

GET /ajax/phenotypes/withOrg/like/datatables/?draw=1&columns=%5Bobject+Object%5D%2C%5Bobject+Object%5D%2C%5Bobject+Object%5D%2C%5Bobject+Object%5D%2C%5Bobject+Object%5D%2C%5Bobject+Object%5D&order=%5Bobject+Object%5D&start=0&length=10&search=%5Bobject+Object%5D

or in decoded form (output from firebug)

 columns    [object Object],[object Object],[object Object],[object Object],[object Object],[object Object]
    draw    1
    length  10
    order   [object Object]
    search  [object Object]
    start   0

so I serialized the data before sending

$(document).ready(function() {
            $('#example').dataTable( {
                "bServerSide": true,
                "fnServerData": function (sSource, aoData, fnCallback) {
                    var myData = JSON.stringify(aoData);
                    $.ajax({
                        "dataType": 'json',
                        contentType: 'application/json',
                        "type": "GET",
                        "url": "http://localhost:3000/ajax/phenotypes/withOrg/like/datatables/",
                        "data": myData,
                        "success": fnCallback,
                        "error": function () {
                            alert('have some problem');
                        }
                    });
                }                   
            } );
        } );

here is the generated GET parameters from datatables:

GET /ajax/phenotypes/withOrg/like/datatables/?[{%22name%22:%22draw%22,%22value%22:1},{%22name%22:%22columns%22,%22value%22:[{%22data%22:0,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{%22data%22:1,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{%22data%22:2,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{%22data%22:3,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{%22data%22:4,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}},{%22data%22:5,%22name%22:%22%22,%22searchable%22:true,%22orderable%22:true,%22search%22:{%22value%22:%22%22,%22regex%22:false}}]},{%22name%22:%22order%22,%22value%22:[{%22column%22:0,%22dir%22:%22asc%22}]},{%22name%22:%22start%22,%22value%22:0},{%22name%22:%22length%22,%22value%22:10},{%22name%22:%22search%22,%22value%22:{%22value%22:%22%22,%22regex%22:false}}] HTTP/1.1

in decoded form (output from firebug and beautified using an online tool- checked with jslint, seems correct!)

[
   {
      "name":"draw",
      "value":1
   },
   {
      "name":"columns",
      "value":[
         {
            "data":0,
            "name":"",
            "searchable":true,
            "orderable":true,
            "search":{
               "value":"",
               "regex":false
            }
         },
         {
            "data":1,
            "name":"",
            "searchable":true,
            "orderable":true,
            "search":{
               "value":"",
               "regex":false
            }
         },
         {
            "data":2,
            "name":"",
            "searchable":true,
            "orderable":true,
            "search":{
               "value":"",
               "regex":false
            }
         },
         {
            "data":3,
            "name":"",
            "searchable":true,
            "orderable":true,
            "search":{
               "value":"",
               "regex":false
            }
         },
         {
            "data":4,
            "name":"",
            "searchable":true,
            "orderable":true,
            "search":{
               "value":"",
               "regex":false
            }
         },
         {
            "data":5,
            "name":"",
            "searchable":true,
            "orderable":true,
            "search":{
               "value":"",
               "regex":false
            }
         }
      ]
   },
   {
      "name":"order",
      "value":[
         {
            "column":0,
            "dir":"asc"
         }
      ]
   },
   {
      "name":"start",
      "value":0
   },
   {
      "name":"length",
      "value":10
   },
   {
      "name":"search",
      "value":{
         "value":"",
         "regex":false
      }
   }
]

the problem is now that this stringified URL can not be parsed on the express 4 server side I use express4 req.query and url.parse method for this : http://expressjs.com/api.html#req.query and then try to parse the received json string with the JSON.parse() method

...
var url = require('url');
...

 router.get('/withOrg/like/datatables/', function (req, res) {
    console.log('getting json string via req.query');
    console.log(req.query);
    console.log('output parsed json object using JSON.parse');
    console.log(JSON.parse(req.query));

    //another try
    console.log('for stack overflows test 2');
    console.log(url.parse(req.url, true).query);
    console.log('output parsed json object using JSON.parse');
    console.log(url.parse(req.url, true).query);
})

both json string output results are invalid json as you can see here and unable to parse with JSON.parse:

getting json string via req.query

{ '{"data":0,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":1,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":2,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":3,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":4,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":5,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}}': { '{"column":0,"dir":"asc"}': '' } }

output parsed json object using JSON.parse

getting json string via req.query

{ '{"data":0,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":1,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":2,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":3,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":4,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}},{"data":5,"name":"","searchable":true,"orderable":true,"search":{"value":"","regex":false}}': { '{"column":0,"dir":"asc"}': '' } }

output parsed json object using JSON.parse

when I try to parse the json string I get the error from JSON.parse

SyntaxError: Unexpected token o
    at Object.parse (native)
    at module.exports (/Users/xxx/yyy/routes/phenotypesAJAX.js:16:19)
    at Layer.handle [as handle_request] (/Users/xxx/yyy/node_modules/express/lib/router/layer.js:82:5)
    at next (/Users/xxx/yyy/node_modules/express/lib/router/route.js:100:13)

Is this a bug in express 4? I cannot see where the problem is. On the client-side the serialized datatable GET request seems valid (checked with JSLint). On the express4 server side I cannot find any other way to parse the GET request in a different way.

Thank you so much for your help, Oliver

解决方案

I have got the answer from posting this problem at the express github bugtracker. Lesson learned: I was thinking to complicated, express.js request methods are not written especially for a specific request format! They just use the data format which was send to them without modification!

The method I used first:

req.query 

[..] only works with standard query strings, which are key=value pairs, which the URL you gave was not.[..]

The correct method to solve my problem is:

  url.parse(req.url).query

returns the complete parameter string of an URL which than has to be decoded manually:

  obj = JSON.parse(decodeURIComponent(query))

Here is the full explanation: https://github.com/strongloop/express/issues/2460

这篇关于express.js 4 GET请求中的JSON解析问题(从数据表请求数据)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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