2014-05-06 49 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,並在客戶端處理一條錯誤消息。

我希望這會有所幫助。