【问题标题】:Cannot read property 'protocol' of undefined无法读取未定义的属性“协议”
【发布时间】:2014-02-16 07:47:52
【问题描述】:

尝试从 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) 

【问题讨论】:

  • url 中的值是否设置正确? (http(s)://example.com)
  • 网址现在贴在上面
  • URL 参数未定义时,我遇到了这个问题。

标签: javascript ajax angularjs


【解决方案1】:

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

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

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

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

【讨论】:

  • 我收到“请求的资源上没有‘Access-Control-Allow-Origin’标头。”现在出错。这个有什么线索吗?
  • 您正在向不同的来源/域发出请求。谷歌“角cors”。
  • 很高兴我能帮助。 ;)
  • 我收到了这个错误,因为我粘贴了一些用于 $.delete 的 $.post 代码,而 $.delete(非常恰当)没有 $.post 的第二个参数(数据)
【解决方案2】:

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

【讨论】:

  • 谢谢。有效。就我而言,这是由于获取了一个反应环境变量。添加该环境变量后我没有重新启动服务器
【解决方案3】:

在 vue 2 项目中,如果您使用 axios 并遇到此错误,请尝试此解决方案。

  • https://www.npmjs.com/package/vue-axios 安装vue-axios
  • 这样使用vue-axios可以去除协议错误
  • import Vue from 'vue'
  • import axios from 'axios'
  • import VueAxios from 'vue-axios' //这一行对于删除 'protocol' ERROR 很重要
  • Vue.use(VueAxios, axios)

【讨论】:

    【解决方案4】:

    从 react 调用 API 时遇到同样的问题。 检查我的代码后,我发现无法找到环境文件中的端点,这导致了错误。

    我所做的只是停止并重新启动 react 应用程序

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-06
      • 1970-01-01
      • 2018-05-24
      • 1970-01-01
      • 2021-01-21
      • 1970-01-01
      • 1970-01-01
      • 2020-04-06
      相关资源
      最近更新 更多