I'm trying for the first time to run a REST server on Nodejs and access it from AngularJS with $resource, and I've run into problems...
I have a controller, which is supposed to load a JSON object (shopping cart) on login for either a known user, or create empty object if the user is new:
myApp.controller('MainCtrl', ['$scope', '$resource', function($scope, $resource) {
$scope.loggedIn = false;
var DataService = $resource('http://localhost:8080/cart/:userId');
$scope.login = function(user) {
DataService.query({userId: user}, function(data) {
// success
$scope.items = data;
$scope.loggedIn = true;
}, function() {
// error
$scope.items = [
{text: '', price: 0, quantity: 0}
];
$scope.loggedIn = true;
});
$scope.username = user;
};
}]);
The server is simple and uses restify:
var restify = require("restify");
var authenticatedUsers = [
{username:'shopper', korb:[
{text:'Many small thigns', price:1.50, quantity:27},
{text:'Nexus 5 red', price:399.0, quantity:1},
{text:'Something special', price:150.0, quantity:2}
]}
];
function respond(req, res, next) {
var name = req.params.name;
var cart;
authenticatedUsers.forEach(function(user) {
if (user.username == name) {
cart = user.korb;
}
})
res.send(cart);
}
var server = restify.createServer();
server.get('/cart/:name', respond);
server.head('/cart/:name', respond);
server.listen(8080, function() {
console.log('%s listening at %s', server.name, server.url);
})
The problem lies in DataService.query({userId: user}, function(data) {
. Although the object gets send from Nodejs server and received in the browser with status code 200 the success callback never gets triggered. Every time I run the login() function with a proper user name the error callback get triggered independent of the result of the GET. What am I doing wrong? The code is rather short and simple, but apparently I'm missing something...
Thanks in advance