无法读取未定义的属性“协议”

新手上路,请多包涵

尝试从 API 获取数据时在控制台中出现该错误。以前有人遇到过这个问题吗?

 var url = "https://api.website.com/get/?type=events&lat=" + localStorage.getItem('latitude')
+ "&lng=" + localStorage.getItem('longitude') + "&distance=50";

$http({
    headers: {
        'Content-type': 'application/json'
    }
})

$http.get(url).success(function (events) {
    $scope.events = events;
});

错误:

 TypeError: Cannot read property 'protocol' of undefined
at Gb (http://localhost:38772/www/js/plugins/angular.min.js:114:238)
at s (http://localhost:38772/www/js/plugins/angular.min.js:65:249)
at new EventsController (http://localhost:38772/www/js/angular.js:4:5)
at d (http://localhost:38772/www/js/plugins/angular.min.js:30:452)
at Object.instantiate (http://localhost:38772/www/js/plugins/angular.min.js:31:80)
at http://localhost:38772/www/js/plugins/angular.min.js:61:486
at http://localhost:38772/www/js/plugins/angular.min.js:49:14
at q (http://localhost:38772/www/js/plugins/angular.min.js:7:380)
at E (http://localhost:38772/www/js/plugins/angular.min.js:48:382)
at f (http://localhost:38772/www/js/plugins/angular.min.js:42:399)

原文由 user2901304 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 231
2 个回答

您正在发出格式错误的 $http 请求。

您不应该在对 $http 的单独调用中设置标头。调用 $http() 实际上会发出请求,但由于您只使用标头(没有 url 或方法)配置它,它会向您抛出该错误(如预期的那样)。

如果你想设置你的标题,你需要通过将自定义配置对象作为第二个参数传递给你的 $http.get() 调用来实现:

 $http.get(url, {
  headers: {
    'Content-type': 'application/json'
  }
}).success(function (events) {
  $scope.events = events;
});

原文由 Stewie 发布,翻译遵循 CC BY-SA 3.0 许可协议

当请求出现问题时会发生此错误,例如。如果您将 url 设置为未定义的、无效的方法或无效的内容类型,则请求对象的任何错误都会抛出此错误。

原文由 Laxmikant Dange 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题