2016-09-04 50 views
1

我有這樣的代碼

var body="ok"; 
var suc=0; var failed=0; 
$http({ 
      url: API.toUrl('api/xxxx/xxxx'), 
       method: 'POST', 
       data: body 
      }).then(function(response) { 
       if(response.status==200){ 
        suc=suc+1; 
       } 
       if(response.status==400){ 
        failed=failed+1; 
       }       
      }); 

我在這個問題是我無法獲得400個狀態碼,我只得到200而不是400 。如何在我的response參數中獲得400個狀態碼。

我在Angular工作,想要獲得400的任何想法?

感謝

+0

我想,如果響應狀態是400和一個變量,但我不能與response.status處理 – ZizouJd

+0

嘿@Jhonny阿豐索,你有沒有看到我的解決方案? –

回答

0

400狀態代碼會爲錯誤,then接受兩個函數作爲參數第一個用於確定響應和第二個錯誤,所以你必須抓住400的誤差函數。

所以,如果你想抓住它,你應該做這樣的:

var body = "ok"; 
    var suc = 0; 
    var failed = 0; 
    $http({ 
     url: API.toUrl('api/xxxx/xxxx'), 
     method: 'POST', 
     data: body 
    }).then(
     function(response) { 
     if (response.status == 200) { 
      suc = suc + 1; 
     } 
     }, 
     function(error) { 
      //Catch 400 here 
     } 
); 
0

如果您使用的是PHP服務器來寫你的API /服務,那麼請使用以下行手動發送400$http要求

<?php 

// Get the current response code and set a new one 
var_dump(http_response_code(400)); 

// Get the new response code 
var_dump(http_response_code()); 
?> 

[更新] 你可以在這裏看到更多的例子來檢查如何發送響應代碼: PHP: How to send HTTP response code?

+0

你使用PHP服務器發送響應返回給客戶端代碼? –

0

您需要使用錯誤的另一個功能(400):

var body="ok"; 
var suc=0; var failed=0; 
$http({ 
      url: API.toUrl('api/xxxx/xxxx'), 
       method: 'POST', 
       data: body 
      }).then(function(response) { 
       alert response.status ; 
       },function error(response) { 
       alert response.status ; 
      }); 
0

從文檔:

200和299之間的響應狀態代碼被認爲是一個成功狀態,會導致在被調用的成功回調中。任何超出該範圍的響應狀態代碼都被認爲是錯誤狀態,並會導致調用錯誤回調。

- AngularJS $http Service API Reference

var body="ok"; 
var suc=0; var failed=0; 
$http.post(url, data).then(function onSuccess(response) { 
    if(response.status==200){ 
     suc=suc+1; 
    }; 
    //return to chain response 
    return response; 
}).catch(function onReject(errorResponse) { 
    if(errorResponse.status==400){ 
     failed=failed+1; 
    } 
    //throw to chain rejection 
    throw errorResponse;       
}); 

如果從httpPromise鏈接,一定要使用throw聲明中onReject處理程序,以避免拒絕轉換取得成功。