I'm trying to build a webapp and I'm stuck at this part: I want to use Contentful to serve my data. Since it's a RESTful service I thought it would be relatively easy to use. They also have a node module, to make my life even easier. Unfortunately, I can't get the data in my view. After hours of googling and on here I've come up with this, but unfortunately it isn't working.
Server:
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' } } ]
My Controller:
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));
});
}]);
I want to get the movieTitle into my view, but the retrieved data is this:
{"isFulfilled":true,"isRejected":false}
The issue is in your server side code. This example code:
var movies = client.entries({
'content_type': '207BVEIb7GcYeCumc2Cmk4'
}).then(log, log);
Is assigning a Promise to the movies variable. Unfortunately, it's a promise for the result of the log function, so you should change it to this:
var movies = client.entries({
'content_type': '207BVEIb7GcYeCumc2Cmk4'
});
The next problem is that you are never calling then on the promise to get it's resolved value. The simplest way to deal with this (assuming you never want the movie list to be refreshed) is to just call then inside your request handler:
app.get('/api/data/movies', function(req, res, next) {
movies.then(res.json, next);
});
This sets up res.json to run if the movies promise resolves successfully, and next to handle any errors.
If you want the list of movies to be re-retrieved on each request, then you could move the client.entries call into your request handler as well:
app.get('/api/data/movies', function(req, res, next) {
client.entries({
'content_type': '207BVEIb7GcYeCumc2Cmk4'
}).then(res.json, next);
});
One final note: it's also possible (and encouraged) to perform these requests directly from the browser, so you wouldn't even need the express app to proxy requests.