当响应类型为 arraybuffer 时,如何从 HTTP get 方法读取 Angular JS 中的 RAW JSON?

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 状态标记为错误请求时,即使将配置更改为 [= 我也无法读取 JSON 响应54=]='application/json'.

它在 response.data 上只显示空的 ArrayBuffer {}

但重要的是,我可以在 google chrome 开发者工具请求中看到 JSON 响应。

我 googled,搜索堆栈溢出但没有找到太多。

后面添加的行

我正在添加响应 object 图片和数据 从 chrome 网络连接接收图片。

第一张图片:来自 angular JS 的错误函数的响应 object。

第二张图片 - 服务器返回正确的 JSON 消息

第三张图片 - 请求和响应 Header 图片

我面临的唯一问题是无法读取响应数据,因为我将响应类型设置为 arraybuffer

如果 responsetype 是 arraybuffer,要查看它,您应该将其转换为 blob 并从该 blob 创建一个 objectUrl,然后下载它或在新的 tab/browser 中打开 window 查看它。

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);
});

与其期望 arraybuffer 为什么不一直期望 application/json,那么当您 return 应该创建 pdf 的数据时,对数据进行 base64,将它在 json 对象中 return 到客户端

即使抛出异常,您仍然期望 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
}

您甚至不需要解码数据,您只需 create a blob object, then trigger a download 来自 blob