3

I'm building an AngularJS app which calls a NodeJS server that gets data from a DB. The NodeJS returns a JSON.stringify(someArrayWithData).

Here is the AngularJS code:

$scope.getMainGroups = function(){
    $http.jsonp("http://127.0.0.1:3000/get/MainGroups?callback=JSON_CALLBACK").success(function(data, status, headers, config) {
            $scope.MainGroups = data;
        }).error(function(data, status, headers, config) {
            $scope.MainGroups = status;
        });
};

$scope.MainGroups is going to the .error instead to the success even when I can see in the chrome debugger that the result came back (200 ok).

What am I missing?

Alon
  • 3,734
  • 10
  • 45
  • 64

2 Answers2

6

You must return a valid JSON response on the server side. The 200 OK is just the GET request that is injected into the DOM. I bet you are not returning a valid JSON response from the server with right response code.

Here is an example on how to construct the response on the server side (PHP): Simple jQuery, PHP and JSONP example?

Community
  • 1
  • 1
Uku Loskit
  • 40,868
  • 9
  • 92
  • 93
  • 1
    I'm using node.js as my server side and I'm returning res.send(JSON.stringify(mainGroupsArray)); – Alon Aug 03 '13 at 16:03
0

As answered here you need to change the NodeJS response. The JSONP answer needs to start with the exact text that AngularJS added in the URL (for example 'angular.callbacks._1').

// changes in your server script used by NodeJS
// Required for JSONP calls, 'callback' matches the '?callback=JSON_CALLBACK'
app.set('jsonp callback name', 'callback'); 

// ... in your response change json to jsonp
res.jsonp(votes);

After doing these changes, when the server detects a 'callback' in the parameters, answers like this:

/**/ typeof angular.callbacks._1 === 'function' && angular.callbacks._1([{"votes":3,"title":"new topic", etc...

Now yes, AngularJS correctly calls back the 'success' function.

Community
  • 1
  • 1
Carlos Morales
  • 5,676
  • 4
  • 34
  • 42