سؤال

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

هل كانت مفيدة؟

المحلول 2

While Firefox did not produce any error while getting the data from the REST server, Chrome did. This helped me to discover that my server needs to user cors (Cross-origin resource sharing). After including cors into nodejs everything works now.

In case someone is interested, here is the new server. Uses Express instead of Restify though.

var express = require('express'), cors = require('cors');
var app = express();

app.use(express.bodyParser());
app.use(cors());
app.use(app.router);

var users = [
{name:'shopper', cart:[
                        {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}
                    ]
}];

app.get('/cart/:id', function(req, res) {
var id = req.params.id;
console.log('id = ' + id)
var cart = [];
users.forEach(function(user) {
    if(user.name === id) {
        console.log('found the user');
        return res.json(user.cart);
    }
});
res.statusCode = 404;
return res.send('Error 404: User not found');
});

app.post('/cart', function(req, res) {
console.log('POST');
if(!req.body.hasOwnProperty('name') || 
    !req.body.hasOwnProperty('cart')) {
    res.statusCode = 400;
    return res.send('Error 400: Post syntax incorrect.');
}

var newCart = {
    name: req.body.name,
    cart: req.body.cart
};

users.push(newCart);
console.log(newCart);
res.json(true);
});

app.listen(process.env.PORT || 3000);

نصائح أخرى

You're sending userId and not username in the call?

DataService.query({userId: user}, function(data) {
    // success
    $scope.items = data;
    $scope.loggedIn = true;
}...

Should this be:

DataService.query({username: user}, function(data) {
    // success
    $scope.items = data;
    $scope.loggedIn = true;
}...
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top