Search code examples
javascriptangularjsjsonp

JSONP not working in AngularJS as expected


The first commented $scope.url which I took from angular documentation works fine, similarly I am trying to invoke another public url which gives me back the response but always goes to error callback.

Both the URLs are in public domain, so please feel free to try.

                $scope.method = 'JSONP';
             // URL 1: Working
             // $scope.url = 'https://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero';

             // URL 2: Not working (Getting response with status 200OK but going to error callback)           
                $scope.url= 'http://apps.nlm.nih.gov/medlineplus/services/mpconnect_service.cfm?callback=JSON_CALLBACK&mainSearchCriteria.v.cs=2.16.840.1.113883.6.96&mainSearchCriteria.v.c=41381004&knowledgeResponseType=application/javascript';

                $scope.fetch = function() {
                    $scope.code = null;
                    $scope.response = null;

                    $http({method: $scope.method, url: $scope.url, cache: $templateCache}).
                        success(function(data, status) {
                             console.log(data);
                             console.log(status);
                        }).
                        error(function(data, status) {
                            console.log(data);
                            console.log(status);
                        });
                };

enter image description here


Solution

  • For some reason dots are stripping from callbacke method name http://apps.nlm.nih.gov/medlineplus/services/mpconnect_service.cfm?callback=angular.callbacks._0&mainSearchCriteria.v.cs=2.16.840.1.113883.6.96&mainSearchCriteria.v.c=41381004&knowledgeResponseType=application/javascript

    This response can’t be handle by AngularJS as Angular wants to call angular.callbacks.0

    Some development background

    var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
        function() {
            if (callbacks[callbackId].data) {
                completeRequest(callback, 200, callbacks[callbackId].data);
            } else {
                completeRequest(callback, status || -2);
            }
            callbacks[callbackId] = angular.noop;
    });
    

    Every URL that has JSON_CALLBACK string inside will be replaced by angular.callbacks.{\D}

    source: AngularJS.js