سؤال

I have a web app that makes multiple XHR requests to different web services. I'm having issues making calls to the Federal Register API. From the documentation here it suggests:

A simple JSONP interface is also possible; simply add a callback=foo CGI parameter to the end of any URL to have the results be ready for cross-domain JavaScript consumption

Based on the Angular docs I need to use &callback=JSON_CALLBACK.

I've set this request up the exact same way as I have with other jsonp calls in this view, but the Federal Register call is returning an error Unexpected token :. The JSON is coming through, and it's wrapped in a function defined by Angular: articles.json?angular.callbacks._4, which is what I'd expect. Maybe I've made a simple mistake, but as far as I can tell this is set up just like my other XHR requests.

From the Console:

enter image description here

My service:

angular.module('atRiskApp.services')

.factory('FederalRegister', [ '$http', function ($http) {
    var searchRegisterByName = function ( sciName ) {
        var url = 'http://www.federalregister.gov/api/v1/articles.json?per_page=20&order=newest&conditions%5Bterm%5D=' + sciName + '&callback=JSON_CALLBACK';
        var promise = $http.jsonp( url );
        return promise;
    };

    return {
        searchRegisterByName: searchRegisterByName
    }
}]);

Controller:

FederalRegister.searchRegisterByName($scope.codes.sciName).then(function (response) {
  $scope.registerDocs = response.data;
});

Edit: Here is the URL for a sample API call. The data is correctly wrapped in a JSON_CALLBACK(); what's wrong??

Edit 2: The API has a form for constructing API calls. I see that the content-type returned by the API is application/json rather than application/javascript could this be causing a problem?

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

المحلول

I realized that the component that I was adding to the URL was not being encoded. This led to a space being included in the API call. For whatever reason the API call succeeded in returning JSONP, but I was still getting an error.

I switched the URL in my service to encode the scientific name before making the api call:

angular.module('atRiskApp.services')

.factory('FederalRegister', [ '$http', function ($http) {
    var searchRegisterByName = function ( sciName ) {
        var url = 'http://www.federalregister.gov/api/v1/articles.json?per_page=20&order=newest&conditions%5Bterm%5D=' + encodeURIComponent(sciName) + '&callback=JSON_CALLBACK';
        return $http.jsonp( url );
    };

    return {
        searchRegisterByName: searchRegisterByName
    }
}]);

The key bit being encodeURIComponent(sciName) in the url declaration.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top