programing

responseType이 어레이 버퍼인 경우 $http에서 JSON 오류 응답을 읽는 방법

muds 2023. 3. 12. 11:23
반응형

responseType이 어레이 버퍼인 경우 $http에서 JSON 오류 응답을 읽는 방법

다음을 사용하여 바이너리 데이터를 로드합니다.

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

오류가 발생하면 서버는 다음과 같은 오류 JSON 개체로 응답합니다.

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

성공 응답과 다른 유형의 오류 응답을 얻을 수 있는 방법이 있습니까?

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

편집: @Paul LeBeau가 지적한 바와 같이 응답은 ASCII 인코딩으로 간주됩니다.

기본적으로 ArrayBuffer를 문자열로 디코딩하고 JSON.parse()를 사용하면 됩니다.

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

IE11과 Chrome에서 테스트를 실시했는데 정상적으로 동작합니다.

@smkanadl의 답변은 응답이 ASCII라고 가정합니다.응답이 다른 인코딩으로 되어 있으면 작동하지 않습니다.

최신 브라우저(예:FF 및 Chrome, 그러나 IE는 아직 지원되지 않음)는 현재TextDecoder이 인터페이스로 부터 스트링을 디코딩할 수 있습니다.ArrayBuffer(를 통해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);
}

서비스에 다음과 같은 함수를 사용하고 있다고 가정합니다. 이것은 각도 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());    
}

반환할 때 res.json이 아닌 res.json()임을 확인하십시오.이 문제가 있는 모든 사람에게 도움이 되길 바랍니다.

언급URL : https://stackoverflow.com/questions/30052567/how-to-read-json-error-response-from-http-if-responsetype-is-arraybuffer

반응형