我一直在追踪为什么当状态码小于200和大于300时,我无法使用$http在angularjs中看到我的webapi的响应。
我已经调试了angular.js,直到我知道发生了什么(基本上它丢弃了包含我关心的数据的承诺,如果状态码不被认为是成功的,则创建一个没有它的新的承诺)
https://github.com/angular/angular.js/blob/master/src/ng/q.js#L270-L280上的-see代码
this.$$state.value (持有http响应)在这一点上由于某种原因而丢失。
省略原始值有意义吗?我不会在不问我是对是错的情况下提交bug报告的。
这一切背后的原因是我正在服务器端处理一些信用卡信息。如果处理器说这是一张无效的卡,我不会认为这是一个200代码,对吧?请看这个问题的答案……建议使用400条业务规则。这在angularjs中仍然失败。
What is the appropriate HTTP status code response for a general unsuccessful request (not an error)?
此外,仅供参考,httpInterceptors也不起作用,因为它们是在这种“promise替换”发生后使用的。
发布于 2016-03-05 22:25:57
从文档中:
如果响应状态码在200到299之间,则认为是成功状态,会导致调用成功回调。超出该范围的任何响应状态代码都被视为错误状态,并将导致调用错误回调。
— AngularJS $http Service API Reference - General Usage
$http服务拒绝200到299范围之外的响应,但它不会“丢弃消息响应”。使用整个响应对象调用$http promise的resolve和reject方法。
这意味着所有数据在拒绝处理程序中都可用。
var dataPromise = $http(configObject)
.then (function onFulfilled(response) {
//return data for chaining
return response.data;
})
.catch (function onRejected(response) {
if (response.status == 400) {
console.log("400 Bad Request");
console.log("REASON:", response.data);
//chain with default data
return defaultData;
} else {
//throw to chain rejection
throw response;
}
});在上面的示例中,拒绝处理程序记录状态为400的消息的响应,并且将拒绝转换为已履行的默认数据。所有其他状态响应都被链接为拒绝。
数据不会被丢弃;它是可用的,并且可以在拒绝处理程序中使用。
有关链接promises的更多信息,请参阅Angular execution order with $q。
发布于 2016-01-07 01:12:37
您是否在使用promise回调时编写状态代码,然后是捕获,最后是在$resource调用之后。
下面是我要检查的内容:
MyRestAPI.XXX({resource}, {data}, MyCallbackFunction).$promise.catch(function(response) {
//should be called upon error
//check response.status for HTTP code.
}).then(function() {
// OK
});https://stackoverflow.com/questions/34638273
复制相似问题