Search code examples
javascriptangularjsjsonpangular-http

Angular $http.jsonp failing


I'm trying to fetch the results from this endpoint. Using GET I get CORS error so I'm trying jsonp.

The results are

Refused to execute script from 'https://api.airbnb.com/v2/listings/16218947?client_id=3092nxybyb0otqw18e8nh5nty&_format=v1_legacy_for_p3&callback=angular.callbacks._0' 
because its MIME type ('application/json') is not executable, 
and strict MIME type checking is enabled.

My code is

var API_BASE_URL = 'https://api.airbnb.com/v2/';

function getListing(id) {
  var url = API_BASE_URL + 'listings/' + id + '?client_id=3092nxybyb0otqw18e8nh5nty&_format=v1_legacy_for_p3';

  var trusted = $sce.trustAsResourceUrl(url);

  return $http.jsonp(trusted, {
    jsonpCallbackParam: 'callback',
    headers: {
      'Accept': 'application/javascript'
    }
  });
};

Solution

  • The reason you are getting this error is because the endpoint, even that you specified a callback parameter, still returns JSON which probably means that the endpoint doesn't support JSONP either.

    See here: https://api.airbnb.com/v2/listings/16218947?client_id=3092nxybyb0otqw18e8nh5nty&_format=v1_legacy_for_p3&callback=angular.callbacks._0

    This is JSON and not JSONP content which is what the server needs to return in this case.

    Basically the way that the $http.jsonp is implemented is that it injects a <script> element in your DOM with its src property pointing to the url provided. But since the server doesn't wrap the JSON into a callback function (JSONP), this cannot be included as a valid script and thus the resulting error.

    Since CORS and JSONP are not options, you might need to write a server side script on your domain that will act as a proxy between your domain and the remote one. Then send the AJAX request to your script.