如果responseType为arraybuffer,如何从$ http读取JSON错误响应 [英] How to read JSON error response from $http if responseType is arraybuffer
本文介绍了如果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屋!
查看全文