如何在带有 AngularJS 控制器的 $http.get 中指定 MongoDB key/value 参数?
How do I specify MongoDB key/value parameters in an $http.get with an AngularJS controller?
我正在为 Web 应用程序使用 MEAN 堆栈。在我的 controller.js 中,我有以下内容:
var refresh3 = function() {
$http.get('/users').success(function(response) {
console.log("I got the data I requested");
$scope.users = response;
$scope.contact3 = "";
});
};
refresh3();
这将从我的 MongoDB 中拉回 "users" 集合中的每个对象。例如,我如何向其中添加参数以仅带回 "name" : "Bob" 的对象?我尝试使用以下方法在“/users”括号中添加参数:
$http.get('/users', {params:{"name":"Bob"}})
我也尝试过它的变体,但没有成功。任何帮助将不胜感激!
如果您的服务器正在接收数据
(而且应该如此,因为 $http.get('/users', {params:{"name":"Bob"}})
是正确的)
在服务器端,使用查询字符串:
req.query
像这样:
app.get('/users', function(req,res){
if(req.query.name){
db.users.find({"name":req.query.name},function (err, docs) { console.log(docs); res.json(docs); });
}
else{
db.users.find(function (err, docs) { console.log(docs); res.json(docs); });
}
});
发生了什么问题?
您在评论中暗示您的服务器已设置为响应 app.get('/users')
GET 请求,如下所示:
db.users.find(function (err, docs) {
// docs is an array of all the documents in users collection
console.log(docs); res.json(docs); }); });
所以我相信您的 angularjs $http get 是正确的,并且您的服务器正在按应有的方式接收参数 {"name":"Bob"}
;
它只是不知道如何处理它们:
它所做的只是 return 在 app.get('/users')
GET 请求的特定情况下的整个集合。
如何为 REST 配置服务器
您不必在服务器上重新发明轮子。
相反,您可以考虑使用中间件来自动执行任务(在本例中,任务是在您从客户端收到带有参数的获取查询时发出适当的 MongoDb 请求)
我正在为 Web 应用程序使用 MEAN 堆栈。在我的 controller.js 中,我有以下内容:
var refresh3 = function() {
$http.get('/users').success(function(response) {
console.log("I got the data I requested");
$scope.users = response;
$scope.contact3 = "";
});
};
refresh3();
这将从我的 MongoDB 中拉回 "users" 集合中的每个对象。例如,我如何向其中添加参数以仅带回 "name" : "Bob" 的对象?我尝试使用以下方法在“/users”括号中添加参数:
$http.get('/users', {params:{"name":"Bob"}})
我也尝试过它的变体,但没有成功。任何帮助将不胜感激!
如果您的服务器正在接收数据
(而且应该如此,因为 $http.get('/users', {params:{"name":"Bob"}})
是正确的)
在服务器端,使用查询字符串:
req.query
像这样:
app.get('/users', function(req,res){
if(req.query.name){
db.users.find({"name":req.query.name},function (err, docs) { console.log(docs); res.json(docs); });
}
else{
db.users.find(function (err, docs) { console.log(docs); res.json(docs); });
}
});
发生了什么问题?
您在评论中暗示您的服务器已设置为响应 app.get('/users')
GET 请求,如下所示:
db.users.find(function (err, docs) {
// docs is an array of all the documents in users collection
console.log(docs); res.json(docs); }); });
所以我相信您的 angularjs $http get 是正确的,并且您的服务器正在按应有的方式接收参数 {"name":"Bob"}
;
它只是不知道如何处理它们:
它所做的只是 return 在 app.get('/users')
GET 请求的特定情况下的整个集合。
如何为 REST 配置服务器
您不必在服务器上重新发明轮子。
相反,您可以考虑使用中间件来自动执行任务(在本例中,任务是在您从客户端收到带有参数的获取查询时发出适当的 MongoDb 请求)