角$ http.get具有空响应的数据,如果服务器响应500内部服务器错误

问题描述:

请参阅的jsfiddle http://jsfiddle.net/vom4za2z/7/

我用$ http.get赶上响应数据时,服务器响应错误500内部服务器错误。

但在错误回调函数,它送花儿给人返回与数据= NULL和状态响应对象= -1

入住的谷歌Chrome浏览器的开发人员工具“网络”选项卡,你会看到从状态服务器响应代码是500和响应数据,如:

{ 
"AppCode": null, 
"HttpCode": 500, 
"Url": "\/api\/categories\/getList.json", 
"Message": "Expired token", 
"Details": null 
} 

我做错了什么?我如何获得响应数据?

感谢您的帮助,

+0

你有没有仔细检查承载令牌有效? –

+0

令牌已过期,我想在这种情况下捕获错误响应数据 –

使用.success.error在你的API调用。斯波,当它的状态会是200或成功然后它会走向成功块,否则会出错块..

试试这个

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
    <title></title> 
 
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.5.11/angular.min.js"></script> 
 
    <script type="text/javascript"> 
 
    angular.module("app", []).controller('Controller', Controller); 
 

 
    function Controller($scope, $http) { 
 
     $http.defaults.headers.common.Authorization = 'Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEsImV4cCI6MTQ5MjM5OTQ5NX0.oAmERuuIssgRfArS9WMJ74p5afg114CCaLDGIL7k8K4'; 
 
     $scope.success = $scope.error = false; 
 
     $scope.getCode = function (code) { 
 

 
     var cateData = $http.get('https://cloudorder.vn/api/categories/getList.json'); 
 
     cateData.success(function(res, status) { 
 
      console.log(res); 
 
      console.log(status); 
 
     }) 
 
     .error(function(data, status) {  
 
      console.log(data); 
 
      console.log(status); 
 
     }); 
 

 

 

 
     // $http.get('https://cloudorder.vn/api/categories/getList.json').then(
 

 
     // function (data) { 
 
     //  $scope.success = true; 
 
     //  $scope.error = false; 
 
     //  $scope.data = data 
 
     // }, 
 

 
     // function (reason) { 
 
     //  $scope.success = false; 
 
     //  $scope.error = true; 
 
     //  $scope.data = reason 
 
     // }); 
 
     } 
 
     $scope.get200 = function() { 
 
     return $scope.getCode(200) 
 
     }; 
 
    } 
 

 

 
    </script> 
 
</head> 
 
<body> 
 

 
    <div ng-app="app" ng-controller="Controller" class="container"> 
 
    <h4>Response data catched on Developer tool but not in $http.get</h4> 
 
    <pre>{ 
 
     "AppCode": null, 
 
     "HttpCode": 500, 
 
     "Url": "\/api\/categories\/getList.json", 
 
     "Message": "Expired token", 
 
     "Details": null 
 
    }</pre> 
 
    <br/> 
 
    <br/> 
 
    <button ng-click="get200()">GET</button> 
 
    <p ng-show="success">Success!</p> 
 
    <p ng-show="error">Error!</p> 
 
    <p>{{data}}</p> 
 
    </div> 
 
</body> 
 
</html>

+0

谢谢@Saurabh Agrawal,但是在我的代码中,它会更正块而没有响应数据。其他方面.success和.error已弃用,并已在角度1.6(https://docs.angularjs.org/guide/migration#migrate1.5to1.6-ng-services-$http)中删除 –