在角度中,如果服务器响应{错误:'ok'},则$http去捕获
In angular make $http go to catch if server response with {error:'ok'}
$http.get('/data.json')
.then(function(){console.log('ok'})
.catch(function(){console.log('no ok')})
服务器响应为:
200 OK
content-type: application/json
{error:'cannot get the data'}
我希望回应会去.catch
而不是.then
.
我知道我可以从服务器更改响应标头,但我只想在客户端执行此操作。
换句话说:
我如何使角度$http
承诺服务,认为响应对象中带有"error"键的 200 OK 状态将转到catch
而不是调用 then
函数?
您可以使用拦截器:
yourApp.factory('myInterceptor', ['$q', function($q) {
return {
response: function(response) {
if (response.status === 200 && response.data.error) {
return $q.reject(response);
}
else {
return response;
}
}
};
}]);
$httpProvider.interceptors.push('myInterceptor');
$http.get('/data.json')
.then(function(res){
if(res.error === 'cannot get the data'){
return $q.reject(res)
}
return res;
)
.then(function(){console.log('ok'})
.catch(function(){
console.log('no ok')
})
正如其他人建议的那样,您可以使用角度$q
服务reject()
函数检查您希望将请求视为.then
块内的失败并拒绝的条件
正如@yarons指出的,你可以使用拦截器。但是,你的决定是始终返回 200,即使在error
的情况下,那么为什么你现在想在前端改变这种行为呢?
你的逻辑似乎是这样的:
不要告诉前端抛出错误(也许不显示在 开发控制台或让用户现在(,但在内部将其作为 错误。
对我来说,如果你决定采取这种技巧行为,那就一路走下去,不要四处乱窜。只需在then()
中查找错误消息即可。
因此,按照您的计划进入then()
,然后用if
子句在那里捕获您的错误:
$http.get('/data.json')
.then(function(response){
if(response.data.error) {
$scope.error_message = response.data.error;
return;
}
});
相关文章:
- Meteor如何接收HTTP请求
- 在我的情况下,如何进行http请求
- //而不是在src=“”上使用http://"属性
- 我无法使用angularJs($http)访问服务器
- AJAX简单错误.XMLHttpRequest无法加载http://localhost/mpl/getPage.php.
- 如何将PHP get查询转换为Meteor's HTTP.get()
- 角度异步http自动完成
- 什么's本地node.js服务器和python简单http服务器之间的区别
- 角度http服务器页面刷新404s
- http.listen()在运行时接受终端命令
- IIS动态HTTP响应标头
- spring和angularJS(我得到了类似HTTP状态404的错误)
- 存储$http如何从$http函数(Angularjs)外部获取可访问变量中的响应
- Typescript angularjs$http获取响应类型(避免使用<any>)
- 如何从HTTP上下文对象中获取Post数据
- $http获取逻辑以仅允许 200 OK
- 在角度中,如果服务器响应{错误:'ok'},则$http去捕获
- javascript in 200 ok http response
- HTTP请求返回200 OK,但没有响应内容
- Angular $routeProvider http://localhost/thisapp/ == ok, http