2014-08-30 86 views
2

我有一个我想传递给服务器的ID数组。我在网上看到的其他答案描述了如何在url中传递这些id作为查询参数。我不想使用这种方法,因为可能会有很多ID。这是我曾尝试:

AngularJS:

console.log('my ids = ' + JSON.stringify(ids)); // ["482944","335392","482593",...] 

var data = $.param({ 
    ids: ids 
}); 

return $http({ 
    url: 'controller/method', 
    method: "GET", 
    data: data, 
    headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
}) 
.success(function (result, status, headers, config) { 
    return result; 
}) 

的Node.js:

app.get('/controller/method', function(req, res) { 
    console.log('my ids = ' + JSON.stringify(req.body.ids)); // undefined 
    model.find({ 
     'id_field': { $in: req.body.ids } 
    }, function(err, data){ 
     console.log('ids from query = ' + JSON.stringify(data)); // undefined 
     return res.json(data); 
    }); 

}); 

为什么我在服务器端得到undefined?我怀疑这是因为我使用了$.params,但我不确定。

回答

4

休息GET方法使用URL作为方法,如果你想使用属性data在你的AJAX调用发送的更多信息,你需要的方法更改为POST方法来传输信息。

所以在服务器你改变你的声明:中

app.post(代替app.get(

1

如果您使用ExpressJS服务器端,req.body只包含请求体分析的数据。

随着GET请求,data而不是发送查询字符串,因为they aren't expected to have bodies

GET /controller/method?ids[]=482944&ids[]=... 

而且,查询字符串被解析并分配给req.query

console.log('my ids = ' + JSON.stringify(req.query.ids)); 
// ["482944","335392","482593",...] 
+2

对于通过此方法发送的数据量有限制吗?我担心的是,如果我发送大量ID,它会中断。 – 2014-08-31 01:18:54

相关问题