【问题标题】:Angular http.get calls fail with no error codeAngular http.get 调用失败,没有错误代码
【发布时间】:2016-05-02 16:43:27
【问题描述】:

在 Ionic 框架中,在控制器内部,我有以下非常简单的 Angular http get 调用:

$http({
  method: 'GET',
  timeout: '9999',
  responseType: 'json',
  url: 'see below'
}).then(function successCallback(response) {
      console.log('WORKS');
      alert(response.status);//200 OK
  }, function errorCallback(response) {
      console.log('ERROR');
      alert(response.status);// always empty, why?
  });

  // works:
  // http://maps.googleapis.com/maps/api/geocode/json?address=77379&sensor=true
  // http://www.omdbapi.com/?t=lord

  // fail:
  // http://md5.jsontest.com/?text=1234

当您调用底部的 url 时,其中两个有效,其中两个失败。

为什么会这样?我试过了:

  • 标头编码问题
  • 标头 mime 类型(应用程序/json 和其他)
  • 检查格式错误的 json / 空格
  • 超时(设置为 9999 毫秒)
  • 访问控制允许来源:*

我还能尝试什么?感谢您的帮助!

【问题讨论】:

    标签: angularjs json http ionic-framework


    【解决方案1】:

    我看不出你的问题是什么。看看我的 Plunker:http://plnkr.co/edit/X3TuhyBgs3AOF6ekvwbi?p=preview

    尝试像这样格式化您的 GET 请求:

    $scope.getFromUrl = function(url) {
        $http.get(url).then(function(response){
            $scope.response = response.data;
        },function(){
            alert("no");
        });
    }
    

    【讨论】:

    • 那没用。最后是CORS相关的问题。我只是希望 Firefox/Firebug 会公开说服务器脚本没有正确配置。谢谢。
    【解决方案2】:

    原来这是一个 CORS 问题,但 Firefox 原生调试器和 Firebug 并没有告诉你任何提示。如果您有 PHP 服务器端脚本,请尝试使用以下对我有用的标头:

    header('Access-Control-Allow-Origin: *');
    header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
    header('content-type:application/json; charset=utf-8');
    header("Cache-Control: no-cache, must-revalidate");
    header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");
    

    您也可以使用http://test-cors.org/ 来测试您的服务器端代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-02-15
      • 2022-01-25
      • 1970-01-01
      • 2013-03-20
      • 2015-07-06
      • 1970-01-01
      • 1970-01-01
      • 2019-03-08
      相关资源
      最近更新 更多