Axios의 responseType 4가지 옵션: 다양한 응답 데이터 유형 다루기

Axios는 웹 애플리케이션에서 HTTP 요청을 보내고 응답을 받는 데 사용되는 강력한 JavaScript 라이브러리입니다. Axios의 responseType 옵션은 서버로부터 받아오는 응답 데이터의 형식을 지정하는 데 도움을 주며, 다양한 유형의 데이터를 처리할 수 있게 합니다. 이 블로그 포스팅에서는 responseType 옵션의 다양한 유형과 각각의 사용 용도를 살펴보겠습니다.


1. json

  • 설명: json 은 서버에서 JSON 형식의 응답 데이터를 받을 때 사용됩니다. 서버 응답이 JSON으로 파싱되어 JavaScript 객체로 반환됩니다.
  • 예제:
axios.get('https://example.com/api/data', {
  responseType: 'json', // JSON 형식으로 응답 데이터 받기
})
  .then(response => {
    console.log(response.data); // JSON 데이터를 JavaScript 객체로 사용
  })
  .catch(error => {
    console.error(error);
  });
  • 용도: API에서 JSON 데이터를 요청하고 처리할 때 사용됩니다.


2. text

  • 설명: text 은 응답 데이터를 문자열로 받을 때 사용됩니다. 서버 응답이 문자열 그대로 반환됩니다.
  • 예제:
axios.get('https://example.com/api/textData', {
  responseType: 'text', // 텍스트 형식으로 응답 데이터 받기
})
  .then(response => {
    console.log(response.data); // 문자열 데이터를 사용
  })
  .catch(error => {
    console.error(error);
  });
  • 용도: 일반 텍스트 데이터를 요청하고 처리할 때 사용됩니다.


3. blob

  • 설명: blob 은 응답 데이터를 이진 데이터(Binary Data)로 받을 때 사용됩니다. 이진 데이터는 파일 다운로드 등과 같은 상황에서 유용합니다.
  • 예제:
axios.get('https://example.com/api/image', {
  responseType: 'blob', // 이진 데이터 형식으로 응답 데이터 받기
})
  .then(response => {
    // 이미지 파일 다운로드
    const blobData = new Blob([response.data], { type: 'image/jpeg' });
    const url = window.URL.createObjectURL(blobData);
    const link = document.createElement('a');
    link.href = url;
    link.download = 'image.jpg';
    link.click();
    window.URL.revokeObjectURL(url);
  })
  .catch(error => {
    console.error(error);
  });
  • 용도: 파일 다운로드와 같이 이진 데이터를 요청하고 처리할 때 사용됩니다.


4. arraybuffer

  • 설명: arraybuffer 은 응답 데이터를 ArrayBuffer 형식으로 받을 때 사용됩니다. 이진 데이터를 효과적으로 처리하는 데 사용됩니다.
  • 예제:
axios.get('https://example.com/api/audio', {
  responseType: 'arraybuffer', // ArrayBuffer 형식으로 응답 데이터 받기
})
  .then(response => {
    // ArrayBuffer를 사용하여 오디오 데이터 처리
    const audioContext = new AudioContext();
    audioContext.decodeAudioData(response.data, buffer => {
      const audioBufferSource = audioContext.createBufferSource();
      audioBufferSource.buffer = buffer;
      audioBufferSource.connect(audioContext.destination);
      audioBufferSource.start();
    });
  })
  .catch(error => {
    console.error(error);
  });
  • 용도: 오디오, 비디오 등의 이진 데이터를 요청하고 처리할 때 사용됩니다.


responseType 값은 서버로부터 받아오는 데이터의 유형에 따라 선택되며, 이를 통해 데이터를 적절하게 처리할 수 있습니다. Axios의 responseType 옵션은 다양한 웹 애플리케이션에서 데이터 요청 및 응답 처리에 유용하게 활용됩니다.



Leave a Comment