본문 바로가기

React

[React] Fetch 와 Axios

1. Fetch

 

fetch 는 자바스크립트 내장 라이브러리로, 패키지 설치가 필요 없음. 그러나 다음과 같은 단점이 있음.

- 미지원 브라우저 존재

- 개발자에게 불친절한 response

- axios 에 비해 부족한 기능

 

2. Axios

 

axios 란 node.js 와 브라우저를 위한 Promise 기반 http 클라이언트


[데이터 읽어오기]

 

fetch

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

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

- fetch().then 을 한 상태여도 여전히 JSON 포맷의 응답이 아니기 때문에, response.json()을 한번 더 해주는 과정이 필요함.

- 따라서 fetch로 데이터 요청을 하는 경우 두개의 .then() 이 필요하다.

 

axios

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

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

axios는 응답(response)을 기본적으로 JSON 포맷으로 제공한다. 따라서 response.data 로 사용하면 됨.

 

[에러처리]

 

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);
	  }
	});

 

 

'React' 카테고리의 다른 글

[React] Thunk  (0) 2023.07.04
[React] instance 와 interceptor  (0) 2023.07.04
[React] 비동기 통신 axios(patch)  (0) 2023.07.04
[React] 비동기 통신 axios(delete)  (0) 2023.07.04
[React] 비동기 통신 axios(post)  (0) 2023.07.04