目前我有这样的想法:
$http({
method: 'POST',
url: 'http://api-endpoint/somescript/',
data: formData,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
})
.then(function (response) {
console.log(response);
});如果另一端的脚本运行正常,则调用then。但是,假设服务器端的脚本有某种错误,没有正确捕获。如果我通过抛入一些垃圾调用(如asdfasdf() )来弥补错误,则不会调用then函数,而是在浏览器控制台中得到该函数:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://api-endpoint/somescript/. (Reason: CORS
header 'Access-Control-Allow-Origin' missing).如何在角度代码中捕获它,以便以用户友好的方式处理它?
编辑:这不是一个复制,因为它是特定的角度。
发布于 2015-06-10 23:32:24
$q.then()方法接受三个函数参数,第一个是成功回调的处理程序,第二个是错误,第三个是通知。$http在幕后利用了$q,因此这个thenable应该像文档所建议的那样运行。
要处理上述代码中的错误,只需添加一个额外的函数来处理错误,如下所示:
.then(function (response) {
console.log(response);
}, function(response) {
console.log(response);
});可以随意浏览$q文档,特别是承诺API,以获得更多细节。
发布于 2015-06-10 19:29:46
要处理这个问题,我们必须添加一个服务/工厂来拦截http调用。你可以在你的配置中这样做
$httpProvider.interceptors.push('httpRequestInterceptor'); 现在,上面的服务将是这样的
angular.module("app").factory('httpRequestInterceptor', function ($q) {
return {
'request': function (config) {
// Extract request information
return config || $q.when(config);
},
'responseError': function(rejection) {
// Extract response error information and handle errors
return $q.reject(rejection);
}
}
});https://stackoverflow.com/questions/30765443
复制相似问题