【发布时间】:2013-07-09 16:04:23
【问题描述】:
我创建了一个通过 url 工作的 API,基于 node.js、express.js、mongoDB 和 angular.js。
我的 API 是这样调用的:
app.get('/api/posts/:query', api.postsQuery);
因此,如果我输入 localhost:3000/api/posts/<whateverquery>,mongoDB 会将所有相关的 JSON 吐出到我的浏览器,所以它工作得很好。
但是,我正在尝试将其链接到我的 Angular 前端,这会导致问题。我希望用户能够搜索表单并让我的数据库返回正确的记录。这是我的控制器:
function indexCtrl($scope, $http, $resource) {
$scope.itemSearch = $resource('http://localhost\\:3000/api/posts/:query',
{query:''}, {get:{method:'JSONP'}});
$scope.doSearch = function(){
$scope.posts = $scope.itemSearch.get({query:$scope.searchTerm});
console.log($scope.posts[1]) // returns undefined
}
}
我的问题是,当我运行 $scope.doSearch 时,我在 Chrome 的资源面板中看到这样的查询: 所以确实正在加载正确的数据,但它没有附加到 $scope.posts。
我感觉这可能是因为我需要一个回调函数;我尝试使用callback: JSON_CALLBACK,但这会弄乱我的查询/API(因为它会在$resource 调用的末尾添加一个?callback=...,这会破坏查询)。
关于我可以在这里做什么以使其正常工作的任何想法?问题是缺少回调吗?也许我可以在app.get 调用之后添加一些正则表达式,在:query 之后允许任何通配符>
【问题讨论】:
标签: javascript node.js angularjs