Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read JSON error response from $http if responseType is arraybuffer

I load some binary data using

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

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 ??? */ })
like image 343
hansmaad Avatar asked May 05 '15 12:05

hansmaad


People also ask

What is response type ArrayBuffer?

"arraybuffer" The response is a JavaScript ArrayBuffer containing binary data. "blob" The response is a Blob object containing the binary data.

Which of the following code lines allows an XMLHttpRequest to return binary data?

Which of the following code lines allows an XMLHttpRequest to return binary data? request. responseType = 'binary'; request.


3 Answers

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

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'];

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

like image 190
smkanadl Avatar answered Oct 19 '22 13:10

smkanadl


@smkanadl's answer assumes that the response is ASCII. If your response is in another encoding, then that won't work.

Modern browsers (eg. FF and Chrome, but not IE yet) now support the TextDecoder interface that allows you to decode a string from an ArrayBuffer (via a DataView).

if ('TextDecoder' in window) {
  // Decode as UTF-8
  var dataView = new DataView(data);
  var decoder = new TextDecoder('utf8');
  var response = JSON.parse(decoder.decode(dataView));
} else {
  // Fallback decode as ASCII
  var decodedString = String.fromCharCode.apply(null, new Uint8Array(data));
  var response = JSON.parse(decodedString);
}
like image 28
Paul LeBeau Avatar answered Oct 19 '22 14:10

Paul LeBeau


Suppose in your service, you have a function you are using like, This is for Angular 2

someFunc (params) {
    let url = 'YOUR API LINK';
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Authorization','Bearer ******');
    return this._http
            .post(url, JSON.stringify(body), { headers: headers})
            .map(res => res.json());    
}

Make sure when you return it it is res.json() and not res.json. Hope it helps, to anyone having this issue

like image 1
Adeel Imran Avatar answered Oct 19 '22 13:10

Adeel Imran