【问题标题】:Can AngularJS set the responseType after a response has been received?AngularJS 可以在收到响应后设置 responseType 吗?
【发布时间】:2019-05-15 20:47:58
【问题描述】:

我有一个 Angular 1.x 应用程序,它期望使用 $http.post() 调用接收二进制文件下载 (pdf)。问题是,我还想获得一条以 json 格式发送的处理错误消息。我可以通过配置做到这一点

headers: {
  'Accept': 'application/pdf, application/json'
}

问题是我必须设置responseType: 'arraybuffer',否则 pdf 二进制文件将被转义(或更改为不加载)。但是,这会阻止 json 被正确读取或解释。

我怎样才能两者兼得?

编辑:我会试着澄清一下;可能我的理解有误。

$http({
    method: 'POST',
    url: "/myresource",
    headers: {
        'Accept': 'application/pdf, application/json'
    },
    responseType: 'arraybuffer'
})
.then(
    function(response) {
        // handle pdf download via `new Blob([data])`
    }, function(response) {
        // pop up a message based on response.data
    }
)

在我返回 pdf 数据块和 http 状态为 200 的场景中,第一个函数处理响应并提示用户保存文件。但是,如果状态为错误 (422),则 response.data 未定义。我认为这是因为responseType 正在阻止正确处理 json。

如果我删除 responseType 行,错误数据会被正确读取,但是当保存 pdf 时,某些文件字节不正确并且实际上已损坏。我认为这是因为文件正在被编码,因为 javascript 需要一个字符串。

【问题讨论】:

  • 不要将服务器错误作为成功数据发送。将它们作为错误发送。发送 200 成功并带有错误消息以进行处理只会使 API 使用者感到困惑。
  • @Claies,我没有将错误作为 200 状态发送(它是 422)。
  • @georgeawg,我正在为每个响应设置相应的内容类型。
  • 根据documentation如果将空字符串设置为responseType的值,则假定为“text”类型。所以,我希望如果我不这样做'不要设置它,它正在改变pdf。但是,如果我设置它,它将无法正确处理 json 结果。
  • 我真的不确定我是否理解这个问题;如果您的错误消息处于不同的 http 状态,那么您不需要在标头中接受它的内容类型,除非我完全错了?

标签: angularjs


【解决方案1】:

加载响应后无法更改 XHR responseType 属性。但是arraybuffer可以根据Content-Type进行解码和解析:

 var config = {
    responseType: "arraybuffer",
    transformResponse: jsonBufferToObject,
  };

  function jsonBufferToObject (data, headersGetter, status) {
      var type = headersGetter("Content-Type");
      if (!type.startsWith("application/json")) {
        return data;
      };
      var decoder = new TextDecoder("utf-8");
      var domString = decoder.decode(data);
      var json = JSON.parse(domString);
      return json;
  };

  $http.get(url, config);

上面的示例设置 XHR 返回一个 arraybuffer 并使用一个 transformResponse 函数来检测 Content-Type: application/json 并在必要时对其进行转换。

DEMO on PLNKR

【讨论】:

  • 是的,这就是我要找的(不明白)。
  • AngularJS $http 使用XHR APInew Fetch API 可以同时执行这两种操作或随时更改。
猜你喜欢
  • 2019-02-15
  • 2011-03-21
  • 2021-07-29
  • 2018-01-12
  • 1970-01-01
  • 1970-01-01
  • 2014-08-20
  • 2017-09-20
  • 2016-05-29
相关资源
最近更新 更多