Angularjs Angular(1.5)处理来自使用responseType blob调用的$http的JSON错误

Angularjs Angular(1.5)处理来自使用responseType blob调用的$http的JSON错误,angularjs,Angularjs,我遇到了一个关于$http的问题,名为responseType:blob。 我希望在JSON中处理错误响应,但即使在服务器上将响应的内容类型设置为“application/JSON”,我也会得到blob数据 $http.post(url, data, {responseType: 'blob'}) .then(function(response) { // download the file (works fine) }) .catch(function(error) {

我遇到了一个关于$http的问题,名为responseType:blob。 我希望在JSON中处理错误响应,但即使在服务器上将响应的内容类型设置为“application/JSON”,我也会得到blob数据

$http.post(url, data, {responseType: 'blob'})
  .then(function(response) {
    // download the file  (works fine)
  })
  .catch(function(error) {
    // handle JSON response error
  });

有没有办法不去反对呢?

对于成功和错误案例,你不能有不同的内容类型,但是你可以在一个地方管理转换。编写
responseError
,检查
错误。数据
是否为Blob的
实例
并将其转换为JSON

。然后()函数可以更有效地使用。然后(函数(响应){},函数(错误){console.log(错误);});在console.log()中,您将以希望的方式获取它。然后你就可以处理了。谢谢,但我的项目惯例是使用then().catch()而不是then(onSuccess,onError)。不幸的是,它没有改变OneError回调中的数据仍然是blob类型的事实。您可以尝试$http({method:'GET',url:Restangular.one('attachments',idAtt.).getRestangularUrl(),headers:{X-Auth-Token:'Token},responseType:'blob')。然后(函数(response){var url=(window.url | | | window.webkitURL).createObjectURL(response.data);window.open(url);});嗨,Aleskey,我已经用
拦截器和
文件阅读器的
readAsText
方法修复了它,但我想知道是否有更优雅的方法可以做到这一点。