【问题标题】:Tumblr API Angular $http GET [duplicate]Tumblr API Angular $http GET [重复]
【发布时间】:2017-10-30 13:53:45
【问题描述】:

我在 Tumblr 和 Angular 方面遇到了一个我无法弄清楚的 API 问题。当使用 $http 尝试从某个博客获取信息时,它会保持“预检响应无效”。我想我在看这段代码时会有点眼花缭乱。有人会看看这个并告诉我我做错了什么吗?谢谢。

$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);

});

【问题讨论】:

  • 我在 plunkr 中运行你的代码并得到一个错误,并清楚地描述了问题No 'Access-Control-Allow-Origin' header is present on the requested resource.SO post 中有 24 个答案

标签: angularjs get tumblr preflight angularjs-1.6


【解决方案1】:

您可以像这样更改您的$http 请求:

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

Here's a plunkr 带有工作代码

这似乎工作正常。祝你好运!

【讨论】:

  • 注意: 使用 AngularJS V1.6,您不能再在 JSONP 请求中使用 JSON_CALLBACK 占位符。如需更多信息,请参阅AngularJS Developer Guide - Migrating to V1.6 ($http)
  • 有趣,我没有意识到这一点。谢谢!
  • 这可以解释为什么他的例子对我不起作用,直到我完全复制它并把它放下。无论如何,这很有效,并使我朝着正确的方向前进。谢谢!
【解决方案2】:

这个问题通常是由于 CORS-Cross Origin Resource Sharing 造成的。您尝试访问的第 3 方 API 应该允许来自您的站点的请求。看起来它不允许你这样做,基本上检查你是否可以对该 API 进行 GET 调用的飞行前请求失败了。如link 中所述,有多种方法可以修复它。

【讨论】:

    猜你喜欢
    • 2018-08-26
    • 1970-01-01
    • 2016-04-03
    • 2017-03-12
    • 2016-11-13
    • 2015-04-16
    • 1970-01-01
    • 2017-10-16
    • 1970-01-01
    相关资源
    最近更新 更多