如何使用Node / Express和Angular从服务器发送JSON对象到我的视图
我试图build立一个webapp,我被困在这个部分:我想使用Contentful来服务我的数据。 由于这是一个RESTful服务,我认为这将是相对容易使用。 他们也有节点模块,让我的生活更加轻松。 不幸的是,我看不到数据。 经过几个小时的谷歌search,在这里我已经想出了这个,但不幸的是,它不工作。
服务器:
var client = contentful.createClient({ accessToken: 'token', space: 'id', secure: true, host: 'cdn.contentful.com' }); var log = console.log.bind(console); var movies = client.entries({ 'content_type': '207BVEIb7GcYeCumc2Cmk4' }).then(log, log); app.get('/api/data/movies', function(req, res) { res.json(movies); });
JSON:
[ { sys: { id: '6nEC5yrZwA0YoikiMeQYky', revision: 1, type: 'Entry', locale: 'en-US', contentType: [Object], createdAt: Mon Sep 15 2014 22:16:10 GMT+0200 (CEST), updatedAt: Mon Sep 15 2014 22:16:10 GMT+0200 (CEST), space: [Object] }, fields: { movieTitle: 'Guardians of the Galaxy' } } ]
我的控制器:
angular.module('MyApp') .controller('MainCtrl',['$scope', '$http', function($scope, $http) { $http.get("/api/data/movies").success(function(data){ $scope.movieTitle = data.movieTitle; alert(JSON.stringify(data)); }); }]);
我想要将movieTitle放到我的视图中,但检索的数据是这样的:
{ “isFulfilled”:真实的, “isRejected”:假}
这个问题是在你的服务器端代码。 这个示例代码:
var movies = client.entries({ 'content_type': '207BVEIb7GcYeCumc2Cmk4' }).then(log, log);
将movies
分配给movies
variables。 不幸的是,这是对log
函数结果的承诺,所以你应该把它改为:
var movies = client.entries({ 'content_type': '207BVEIb7GcYeCumc2Cmk4' });
接下来的问题是,你永远不会打电话来承诺解决问题的价值。 处理这个问题的最简单的方法(假设你永远不需要刷新电影列表)就是在你的请求处理程序中调用:
app.get('/api/data/movies', function(req, res, next) { movies.then(res.json, next); });
这设置res.json
运行,如果电影诺言解决成功, next
处理任何错误。
如果您想要在每个请求中重新检索电影列表,则可以将client.entries
调用移动到您的请求处理程序中:
app.get('/api/data/movies', function(req, res, next) { client.entries({ 'content_type': '207BVEIb7GcYeCumc2Cmk4' }).then(res.json, next); });
最后一个注意事项:也可以(并鼓励)直接从浏览器执行这些请求,所以甚至不需要快速应用程序来代理请求。