[HTTP] Fetch vs Axios

zhflsdl보보·2022년 12월 24일
1

CS

목록 보기
3/3

Fetch, Axios 모두 promise 기반의 HTTP 클라이언트이다. 네트워크 요청을 하면 resolve 또는 reject 할 수 있는 promise 가 반환된다.

Fetch는 브라우저에서 제공하는 API 로 따로 설치할 필요가 없다.

Axios는 서드 파티 라이브러리로 패키지 매니저 (npm, yarn) 를 통해 설치해야 하며, 파일에서 import 해서 사용한다.


문법 비교

fetch

fetch(url, {
  method: "GET", // (POST, PUT, DELETE, etc.)
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({}),
});

axios

axios(url, {
  method: "get", // (post, put, delete, etc.)
  headers: {},
  data: {},
});

데이터 처리

fetch

fetch(url)
  .then((response) => response.json())
  .then(console.log);

.json() method 를 호출하여 JSON 형식의 데이터로 바꿔서 반환한다.
일반적인 fetch 요청은 두개의 .then() 호출을 가진다.

axios

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

반면에 axios는 기본적으로 JSON 타입의 데이터를 사용한다.
그리고 데이터는 항상 data 프로퍼티에서 사용할 수 있다.

자동 문자열 변환 (stringify)

데이터를 body에 담아서 보낼 때
fetch는 JSON.stringify()를 사용해서 객체를 문자열로 변환한 뒤 body에 담아야 한다.

fetch

fetch(url, {
  method: "post",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify(todo),
})
  .then((response) => response.json())
  .then((data) => console.log(data));

axios는 자동으로 데이터를 문자열로 변환해주므로 stringify()를 쓰지 않아도 된다.
그리고 데이터는 body에 담는게 아닌 그냥 data에 할당해주면 된다.

axios
  .post(url, {
    headers: {
      "Content-Type": "application/json",
    },
    data: todo,
  })
  .then(response => console.log(response.data));

에러 처리

Promise가 reject 되면 .catch() 를 사용하여 에러를 처리한다.

fetch 는 네트워크 장애가 발생한 경우에만 primise 를 reject 한다.
404 에러나 다른 HTTP 에러 응답은 거부하지 않는다. 따라서 .then을 사용하여 하나하나 처리를 해줘야 하는 단점이 있다.

fetch(url)
  .then((response) => {
    if (!response.ok) {
      throw new Error(
        `This is an HTTP error: The status is ${response.status}`
      );
    }
    return response.json();
  })
  .catch((err) => {
    console.log(err.message);
  });

반면에 axios 는 status code 가 2xx 범위를 넘어가면 reject한다.
따라서 에러에 대한 자세한 정보를 확인할 수 있는 장점이 있다.

axios
  .get(url)
  .then((response) => console.log(response.data))
  .catch((err) => {
  if (err.response) {
  // 요청이 이루어졌고 서버가 응답했을 경우

      const { status, config } = err.response;

      if (status === 404) {
        console.log(`${config.url} not found`);
      }
      if (status === 500) {
        console.log("Server error");
      }

    } else if (err.request) {
      // 요청이 이루어졌으나 서버에서 응답이 없었을 경우
      console.log("Error", err.message);
      
    } else {
      // 그 외 다른 에러
      console.log("Error", err.message);
    }
  });

응답 시간 초과, 요청 취소

axios 의 경우 timeout 속성을 객체에 추가하여 요청이 종료될때까지의 시간을 지정할 수 있다.

axios
  .get(url, {
    timeout: 4000, // default = 0
  })
  .then((response) => console.log(response.data))
  .catch((err) => {
    console.log(err.message);
  });

fetch를 통해 요청을 취소하려면, AbortController() 를 사용할 수 있다.

const controller = new AbortController();
const signal = controller.signal;
setTimeout(() => controller.abort(), 4000);

fetch(url, {
  signal: signal,
})
  .then((response) => response.json())
  .then(console.log)
  .catch((err) => {
    console.error(err.message);
  });
profile
매일매일 성장하는 개발자

0개의 댓글