[英]How to read JSON error response from $http if responseType is arraybuffer
[英]How to read RAW JSON in Angular JS from HTTP get method, when response type is arraybuffer?
我正在尝试阅读ByteArray以将PDF格式的Java显示到Angular JS中
method : 'GET'
url : '',
cache : isCache||false,
responseType: 'arraybuffer'
当一切正常时,这工作正常。
但是,当我使用一些正确的JSON抛出异常并将HTTP Status标记为错误请求时,即使将配置更改为respone.config.responseType ='application / json' ,我也无法读取JSON响应。
它在response.data上只显示空的ArrayBuffer {}
。
但重要的是,我可以在谷歌浏览器开发人员工具请求中看到JSON响应。
我用谷歌搜索,搜索堆栈溢出但没有找到太多。
下面添加了以下行
我正在从chrome网络连接添加响应对象图片和数据接收图片。
第一个图像:角度JS的误差函数的响应对象。
第二个图像 - 服务器返回正确的JSON消息
第三张图片 - 请求和响应标题图片
我设置的唯一问题是无法读取响应数据,因为我将响应类型设置为arraybuffer
而不是期望arraybuffer
为什么不一直期望application/json
,然后当你返回你应该创建你的pdf的数据时,做一个base64的数据,把它放在一个json对象中并将它返回给客户端
即使你抛出异常,你仍然期待JSON
。 您从服务器端的响应可能是这样的:
{
responseCode: // your response code according to whether the request is success or not,
responseMessage: // success or fail
data: // your base64 encoded pdf data(the data that if the request is successful will be returned), note it will be returned as a normal string
} // I'm hoping you know how to base64 encode data
然后在您的客户端(Javascript),执行if
if(data.responseCode == //errorCode) {
alert(data.responseMessage);
} else {
// Unpack data
var myPdfData = // base64 decode(data.data)
// Do logic to create and open/download file
}
您甚至不需要解码数据,只需创建一个blob对象 ,然后从blob 触发下载
如果responsetype是arraybuffer
,要查看它,你应该将它转换为blob并从该blob创建一个objectUrl,并将其下载或在新的选项卡/浏览器窗口中打开以查看它。
JS:
$http.get('your/api/url').then(function(response) {
var blob = new Blob([response.data], { type: 'application/pdf' });
var downloadUrl = URL.createObjectURL(blob);
$timeout(function () {
var link = document.createElement('a');
link.download = 'SOME_FILE_NAME'+ '.pdf';
link.href = downloadUrl;
link.click();
}, 100);
}, function(errorResponse){
alert(errorResponse.error.message);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.