fetch API , Axios

MIN·2025년 2월 6일

weekly

목록 보기
5/31

Fetch APIAxios를 비교했을 때 axios 가 더 유리한 점

fetch: 응답 형식이 JSON 이면 .josn() 메소드 호출 필요
axios: 응답 자동변환이 있기 때문에 호출 필요 없음

사용법

fetch API

fetch('url') 
  .then(res => res.json()) 
  .then(data => console.log(data));

Axios

axios.get('url')
  .then(res => console.log(res.data));

위 코드는 JSON 파싱에 대한 비교

오류처리

Axios

axios.get('url')
  .then(res => console.log(res))
  .catch(error => {
    console.error('에러 발생:', error.res ? error.res.data : error);
  });

axios는 catch블록으로 처리해 400,500번대는 자동으로 처리해준다.(error.res가 존재하면 error.res.data출력

fetch API

fetch('url')
  .then(res => {
    if (!res.ok) {
      throw new Error('응답 오류');
    }
    return res.json();
  })
  .catch(error => console.error('에러 발생:', error));

Axios가 더 많은 기능을 제공하기도하고 훨씬 직관적이어서
사용하지 않을 이유가 없는것 같다.

0개의 댓글