본문 바로가기

개발

fetch와 axios

 

 

Axios와 Fetch는 모두 JavaScript에서 HTTP 요청을 보내는 데 사용되는 도구

하지만 몇 가지 차이점이 있다.

 

  1. 기본 제공 여부:
    • Fetch: Fetch는 최신 브라우저에 내장된 API로, 추가적인 설치 없이 사용할 수 있다.
    • Axios: Axios는 외부 라이브러리로, 사용하려면 npm이나 yarn을 통해 설치해야 함
  2. API 디자인:
    • Fetch: Promise 기반 API를 사용하여 비동기 요청을 처리:
      fetch('https://api.example.com/data')
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.error('Error:', error));
    • Axios: Promise 기반 API를 사용하며, 구성이 Fetch보다 간단:
      import axios from 'axios';
      
      axios.get('https://api.example.com/data')
        .then(response => console.log(response.data))
        .catch(error => console.error('Error:', error));
       
  3. 기본 설정 및 설정 가능성:
    • Fetch: 기본적으로 설정이 제한적. 요청 시 기본적인 설정을 매번 명시해야 함.
    • Axios: 기본 설정을 쉽게 할 수 있으며, 인스턴스를 생성하여 재사용 가능한 설정을 만들 수 있다.
      const axiosInstance = axios.create({
        baseURL: 'https://api.example.com',
        timeout: 1000,
        headers: {'X-Custom-Header': 'foobar'}
      });
  4. 응답 처리:
    • Fetch: Fetch는 응답을 자동으로 JSON으로 변환하지 않는다.
    • Axios: Axios는 응답을 자동으로 JSON으로 변환
       
  5. 지원하는 기능:
    • Fetch: 기본적으로 타임아웃, 요청 취소, 자동 변환 등의 기능을 지원하지 않음.
    • Axios: 타임아웃 설정, 요청 취소, 자동 변환 등의 기능을 내장하고 있다!
const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function (thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
    // handle error
  }
});

// 요청 취소
source.cancel('Operation canceled by the user.');

 

선택 기준

  • 단순한 프로젝트: 간단한 요청을 처리할 경우 Fetch가 충분
  • 복잡한 요구사항: 여러 가지 설정을 필요로 하거나, 요청 취소, 자동 변환 등의 기능이 필요한 경우 Axios가 더 나은 선택

 

 

결론

axios 하자

 

 

 

 

이전 글에 소개한 영상들보다 더 자세한 리액트 쿼리 튜토리얼인데, 뒤에 axios도 나와서 유용할 것 같다.

https://www.youtube.com/watch?v=3e-higRXoaM

 

 

 

 

'개발' 카테고리의 다른 글

useRef  (1) 2024.07.10
axios 관련 폴더 정리  (0) 2024.07.09
"use client"  (0) 2024.07.08
ESLint & Prettier - Airbnb  (0) 2024.07.08
Complex Animations with Framer Motion  (0) 2024.07.08