2014-05-06 50 views
3

$我的AngularJS项目中的http无法识别iOS上的40X(401,403,405 ...)错误。 我使用1.2.10 AngularJS版本和Cordova 3.4.0版本。

下面是我使用的代码:

TE_SERVICES.factory('hello',function ($http,$rootScope) { 
return { 
loginUser: function(userCredentials,successCallback,errorCallback){ 
      $http({ 
       method: "GET", 
       url: "data/example.json", 
       headers: {"Authorization":'Basic '+userCredentials}, 
      }).then(function(response){ 
           successCallback(response.data); 
           console.log("Success------"+JSON.stringify(response)) 
      },function(data, status, headers, config){ 
           errorCallback(data); 
           console.log("Error------"+JSON.stringify(data)+" "+status) 
      }) 

     } 
    } 
}); 

hello.loginUser($rootScope.encodedUserCredencials,function(persons) { 
       // success handler 
      }, function(data) { 
       // error handler 
       console.log(data.status+"===="+status) 
       }); 

data.status将返回0和状态返回undefined。 请帮我解决这个问题。

试过包括IOS.But在白名单中域无解:(它仍然给出了同样的答复。

但相同的代码工作绝对没问题的Android系统。 请帮我解决这个问题。

在此先感谢:)

+0

我有同样的问题。你找到了解决方案吗? –

回答

4

因此,您使用的角度为$http。你使用error回调还是then回调中的第二个功能?

$http.get("someUrl") 
    .success(function(response){}) // if http code == 200 
    .error(function(response){}) // else 

或者与then,可以采取2种功能。第一个是onSuccess,第二个是onError函数。

$http.get("someUrl") 
    .then(function(response){ 
      // if http code == 200 
    }, 
    function(response){ 
      // else 
    }); 

response参数也包含错误代码。

考虑使用$httpInterceptor来处理在同一地点的所有错误代码,而不是在每个http回调中处理它们。

UPDATE: 看起来,角度doc是成功回调不完整/错误。 它不通过4参数。它通过一个response对象,其中包含有关请求+响应和传递数据的所有信息。

更新到编辑

不要自己写回调。使用角承诺:

TE_SERVICES.factory('hello',function ($http,$rootScope) { 
    return { 
     loginUser: function(userCredentials){ 
      return $http({ 
      method: "GET", 
      url: "data/example.json", 
      headers: {"Authorization":'Basic '+userCredentials}, 
      }).then(function(response){ 
      return response.data;          
      },function(response){ 
      return response;         
      });  
     } 
    } 
}); 

hello.loginUser($rootScope.encodedUserCredencials) 
    .then(function(persons) {    // success handler 

    }, function(data) { // error handler 
     console.log(data); 
    }); 

试试这个,告诉我,如果console.log记录一些东西。

+0

我正在使用,编辑了这个问题。请看看。 – Surya

+0

我工作正常在android,问题是在IOS中,当我给android无效的凭据它引发401错误,但在IOS它显示data.status为0. :( – Surya

+1

根据https://docs.angularjs.org/ api/ng/service/$ http“$ http'传统承诺方法'success'和'error'已被弃用,请使用标准的'then'方法。 –

2

我有完全相同的问题。科尔多瓦应用程序,角js,IPhone和401请求没有收到角js http拦截器。他们在Android设备上工作正常。

我的发现是,iPhone浏览器正在处理那些更高的杠杆,并试图使用WWW-Authenticate信息进行身份验证。这就是为什么响应没有达到角度。

我发现的唯一解决方案是在api请求的情况下将我的服务更改为返回400而不是401。在这种情况下,我返回400,并在客户端处理一条错误消息。

我希望这会有所帮助。