aotoyae

[React] Fetch & Axios 의 차이 본문

React

[React] Fetch & Axios 의 차이

aotoyae 2024. 2. 19. 13:51

 

 

💡 두 비동기 통신 라이브러리의 차이점을 알아보자

 

✳️ fetch

  • 미지원 브라우저 존재
  • 개발자에게 불친절한 response
  • axios 에 비해 부족한 기능

✳️ axios

  • 개발자에게 친절한 response(JSON 포맷으로 따로 변경할 필요가 없다!)
  • 상세한 에러 처리 가능

 

1. 데이터를 읽어올 때의 차이점

fetch

const url = "https://jsonplaceholder.typicode.com/todos";

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

 

응답을 JSON 포맷으로 바꾸기 위해 response.json() 을 한 번 더 해줘야 한다.

따라서 두 개의 .then() 이 필요하다.

 

axios

const url = "https://jsonplaceholder.typicode.com/todos";

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

 

친절하게 응답을 기본적으로 JSON 포맷으로 제공한다. 우리는 response.data 로 사용하기만 하면 된다.

 

2. 에러 처리에서의 차이점

fetch

const url = "https://jsonplaceholder.typicode.com/todos";

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

 

fetch 의 경우, catch() 가 동작하는 경우는 오직 네트워크 장애 케이스뿐!

따라서 개발자가 일일히 then() 안의 모든 케이스에 대한 HTTP 에러 처리를 해야한다.

 

axios

const url = "https://jsonplaceholder.typicode.com/todos";

axios
  .get(url)
  .then((response) => console.log(response.data))
  .catch((err) => {
    console.log(err.message);
  });

 

axios.get() 요청이 반환하는 Promise 객체의 상태코드가 2xx 범위를 넘어가면 거부(reject) 를 한다.

이후 곧바로 catch() 부분을 통해 아래와 같이 error handling 이 가능하다!

 

const url = "https://jsonplaceholder.typicode.com/todos";

// axios 요청 로직
axios
  .get(url)
  .then((response) => console.log(response.data))
	.catch((err) => {

		// 오류 객체 내의 response가 존재한다 = 서버가 오류 응답을 주었다	
		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);
	  }
	});