0

I'm running into an API issue with Tumblr and Angular that I can't quite figure out. When using $http to try to get information from a certain blog it keeps 'Response for preflight is invalid'. I think I'm going a bit cross-eyed looking at this code. Will someone look at this and tell me what I'm doing wrong? Thanks.

$scope.tumblrKey = 'mldv2B4xUD5roLX8XfbYdgJhzlgLxfm8mBRuKQhBxXsUFLiqEx';
$scope.tumblrUrl = 'http://api.tumblr.com/v2/blog/whileoutriding.tumblr.com/info?api_key=';

$http({
  method: 'GET',
  headers: {
    'Authorization': $scope.tumblrKey
  },
  url: $scope.tumblrUrl + $scope.tumblrKey
}).then(function successCallback(response) {

    console.log('it worked', response);

  }, function errorCallback(response) {

    console.log('it did not work', response);

});
georgeawg
  • 48,608
  • 13
  • 72
  • 95
Alex Marple
  • 2,908
  • 4
  • 17
  • 24
  • I run you code in plunkr and get an error with a clear description of the problem `No 'Access-Control-Allow-Origin' header is present on the requested resource.` There are 24 answers in this [SO post](https://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource) – Jax May 30 '17 at 07:49

2 Answers2

0

This issue usually comes because of CORS-Cross Origin Resource Sharing. The 3rd party API that you are trying to hit should allow requests from your site. As it seems it is not allowing you to do that, the pre-flight request which basically checks if you can make a GET call or not to that API, is failing. There are multiple ways to fix it as outlined in the link here.

Sujith
  • 1,604
  • 9
  • 16
0

You can change your $http request like so:

$http({
      method: 'jsonp',
      dataType: 'json',
      headers: {
        'Authorization': $scope.tumblrKey
      },
      params: {
        format: 'jsonp',
        callback: 'JSON_CALLBACK'
    },
      url: $scope.tumblrUrl + $scope.tumblrKey
    })

Here's a plunkr with working code

This seems to work fine. Good luck!

Jax
  • 1,839
  • 3
  • 18
  • 30
  • **NOTE:** With AngularJS V1.6, you can no longer use the JSON_CALLBACK placeholder in your JSONP requests. For more information, see [AngularJS Developer Guide - Migrating to V1.6 ($http)](https://docs.angularjs.org/guide/migration#migrate1.5to1.6-ng-services-$http). – georgeawg May 30 '17 at 08:31
  • Interesting, I was not aware of that. Thank you! – Jax May 30 '17 at 08:35
  • That would explain why his example didn't work for me until I copied it entirely and plopped it down. In any case, this works and moves me in the right direction. Thank you! – Alex Marple May 30 '17 at 08:38