[React] axios와 fetch

KJA·2024년 1월 10일
0

간단한 voca기능을 구현해보면서 fetch를 axios의 차이점을 정리하고 fetch에서 axios로 변경해보았습니다.


Axios와 fetch 차이점

Axios

  • Axios는 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리입니다.
  • 주로 API 연동/백엔드랑 프론트엔드 사이의 통신에서 사용됩니다.
  • axios는 json형태로 자동으로 적용해서 response 객체를 바로 반환합니다.

fetch

  • 라이브러리를 import 하지 않아도 사용할 수 있습니다.
  • 지원하지 않는 브라우저가 있습니다.
  • fetch는 JSON.stringify()를 사용하여 객체를 문자열으로 변환한 뒤 body에 할당해야 합니다.

코드 비교

Fetch

    fetch(`http://localhost:5000/words/${word.id}`, {
      method: 'PUT',
      headers: {
        'Accept': 'application/json',
        'Content-Type': 'application/json;charset=UTF-8',
      },
      body: JSON.stringify({
        ...word,
        isDone: !isDone,
      }),
    }).then((res) => {
      if (res.ok) {
        setIsDone(!isDone);
        // let data = res.json();
      }
    });

Axios

axios 파라미터 문법

    await axios({
      method: 'PUT',
      url: `http://localhost:5000/words/${word.id}`,
      data: { // 객체로 넘김
        ...word,
        isDone: !isDone,
      },
    }).then((res) => {
      if (res.statusText === 'OK') {
        setIsDone(!isDone);
      }
    }).catch((e) => console.log(e));;

axios 단축 메소드

    await axios
      .put(`http://localhost:5000/words/${word.id}`, {
        ...word,
        isDone: !isDone,
      })
      .then((res) => {
        if (res.statusText === 'OK') { 
          setIsDone(!isDone);
          // let data = res.data;
        }
      })
      .catch((e) => console.log(e));

[데이터 넘기는 방법]
axios : 객체로 넘김
fetch : string화 해서 넘김

[정상적인 요청/응답 체크]
axios : statusText를 통해서 확인
fetch : response 객체가 ok프로퍼티를 포함하는지 확인

[response 얻는 방법]
axios : response 객체의 data property에 접근하여 얻는다.
fetch : response 객체에 .json() 메소드를 호출하여서 json객체를 얻는다.

0개의 댓글