如果 responseType 是 arraybuffer,如何从 $http 读取 JSON 错误响应 [英] How to read JSON error response from $http if responseType is arraybuffer

查看:30
本文介绍了如果 responseType 是 arraybuffer,如何从 $http 读取 JSON 错误响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用

$http.post(url, data, { responseType: "arraybuffer" }).success(
            function (data) { /*  */ });

如果出现错误,服务器会返回一个错误 JSON 对象,如

In case of an error, the server responds with an error JSON object like

{ "message" : "something went wrong!" }

有什么方法可以获得与成功响应不同类型的错误响应吗?

Is there any way to get the error response in a different type than a success response?

$http.post(url, data, { responseType: "arraybuffer" })
  .success(function (data) { /*  */ })
  .error(function (data) { /* how to access data.message ??? */ })

推荐答案

正如@Paul LeBeau 指出的那样,我的回答假设响应是 ASCII 编码的.

As @Paul LeBeau points out, my answer assumes that the response is ASCII encoded.

基本上你只需要将 ArrayBuffer 解码成一个字符串并使用 JSON.parse().

Basically you just need to decode the ArrayBuffer into a string and use JSON.parse().

var decodedString = String.fromCharCode.apply(null, new Uint8Array(data));
var obj = JSON.parse(decodedString);
var message = obj['message'];

我在 IE11 & 中进行了测试Chrome,这工作得很好.

I ran tests in IE11 & Chrome and this works just fine.

这篇关于如果 responseType 是 arraybuffer,如何从 $http 读取 JSON 错误响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆