2016-09-04 51 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处理程序,以避免拒绝转换取得成功。