请参考jsfiddle http://jsfiddle.net/vom4za2z/7/
当服务器响应错误500内部服务器错误时,我使用$ http.get来捕获响应数据。
但是在错误回调函数中,它总是返回data = null和status = -1
的响应对象签入"网络"在Google Chrome浏览器的开发人员工具标签中,您会看到来自服务器的响应状态代码为500,响应数据如下:
{
"AppCode": null,
"HttpCode": 500,
"Url": "\/api\/categories\/getList.json",
"Message": "Expired token",
"Details": null
}
我做错了什么?我如何获得响应数据?
感谢您的帮助,
答案 0 :(得分:0)
在您的api通话中使用.success
和.error
。 Spo,当它的状态为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>
&#13;