2017-02-27 60 views
1

我已經在谷歌上搜索和堆棧溢出了類似/甚至相同的問題。但我對這個新手並不瞭解如何修正我的代碼。AngularJS 400錯誤的請求不會給予任何迴應

所以,這裏是我的腳本:

$http.post('/authlogin', { 
    email: $scope.userdata.email, 
    password: $scope.userdata.password 
}).then(function(response) { 
    console.log(response); 
    if (response.status == 400) { 
     $scope.errormsg = response.data; 
    } 
    if (response.status == 200) { 
     window.location = '/admin'; 
    } 
}); 

一切都爲200 OK響應工作的罰款。但是,無論何時登錄失敗,API返回400 Bad Request。此時,該錯誤看起來像是甚至沒有用response調用匿名函數。最多的地方爲400的檢查,200,201等是好的&運行完美,但爲什麼不與400

以下是錯誤由AngularJS(美化&除去敏感數據)示於瀏覽器控制檯:

Possibly unhandled rejection: 
{ 
    "data": "Invalid email/password combination.", 
    "status": 400, 
    "config": { 
     "method": "POST", 
     "transformRequest": [null], 
     "transformResponse": [null], 
     "jsonpCallbackParam": "callback", 
     "url": "/authlogin", 
     "data": { 
      "email": "####", 
      "password": "***" 
     }, 
     "headers": { 
      "Accept": "application/json, text/plain, */*", 
      "Content-Type": "application/json;charset=utf-8" 
     } 
    }, 
    "statusText": "Bad Request" 
} 

我不是一個在angular.js中的專業人士,這種行爲和解決方案的解釋將不勝感激。

我的目標是向data返回的用戶顯示錯誤消息。

+0

你嘗試過的誤差函數添加到呢? '.then(function(){// success function},function(){console.log(arguments); //錯誤函數})''。那麼可以使用1個參數作爲函數(僅成功)或2個參數作爲函數(成功和錯誤) – mtizziani

+0

您是否使用表單提交將數據傳遞到服務器端? –

回答

2

$http返回的承諾通過調用第一個匿名函數來解決。如果承諾被拒絕,則會調用第二個匿名函數。這應該做的伎倆。

$http.post('/authlogin', { 
    email: $scope.userdata.email, 
    password: $scope.userdata.password 
}).then(function(successCallback) {  
    if (successCallback.status == 200) { 
     window.location = '/admin'; 
    } 
}, function(errorCallback){ 
    if (errorCallback.status == 400) { 
     $scope.errormsg = errorCallback.data; 
    } 
}); 

更多的例子,閱讀docs

您可以閱讀更多有關承諾here

+0

OMG,@digijap你救了我的一天!感謝此行爲的解釋。 –