본문으로 바로가기

axios와 fetch 무엇이 더 좋을까?

category JavaScript 2025. 1. 7. 15:22

아침에 밥 먹으면서 유툽 뒤적이고 있는데 

↑요 자극적인 썸네일이 있어서 들어가서 대충 보는데 웬걸 내가 즐겨쓰던 axios를 쓰지 않고 native fetch를 사용하는 것으로 요즘 트렌드가 바꼈다는 내용의 댓글도 있어 왜 fetch로 넘어갔는지 궁금해졌습니다.

 

간단하게 말하자면 fetch가 원래 node 환경에서는 실행되지 않았는데 이제 node 환경에서도 지원 가능하고

NextJS에서 edge 런타임에서 잘 동작하지 않는 axios 대신에  fetch를 사용하겠다고 하는 내용입니다.

그리고 fetch는 내장 API로 별도의 의존성 없이 사용할 수 있어 유지 관리에 용이합니다.

 

axios와 fetch를 한번 알아봅시다.

 

1. axios

axios는 외부 API로 npm을 사용해 설치해야 합니다.

const axios = require('axios');
const data = axios.get('https://jsonplaceholder.typicode.com/todos/1');
console.log(data);

 

axios는 Promise 객체를 받아오는 것을 알 수 있습니다.

 

axios
    .get('https://jsonplaceholder.typicode.com/todos/1')
    .then((res) => console.log(res))
    .catch((err) => console.error(err));

 

then()을 이용하여 요청이 성공했을 때의 res는 무슨 정보들을 담고 있을까요??

 

 

res 객체는 status, statusText, headers, config, data 등등... 많은 정보를 담고 있습니다.

그 중 data에 접근하고 싶으니 res.data를 console에 찍어봅시다.

 

2. fetch

fetch는 내장 API로 별도 라이브러리를 설치할 필요가 없습니다.

const data = fetch('https://jsonplaceholder.typicode.com/todos/1')

console.log(data);

 

axios와 마찬가지로 Promise 객체를 반환하는 것을 알 수 있습니다.

const data = fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then((res) => console.log(res))
    .catch((err) => console.error(err));

 

res.body는 응답 본문 데이터를 담고 있는 ReadableStream 객체입니다.

 

 

이 데이터는 원시 스트림 형태로 제공되므로, JSON 데이터로 변환하려면 res.json() 메서드를 호출해야 합니다.

그럼 res.body.json()을 해야하지 않냐고요?

res.json()은 내부적으로 res.body()에 접근하여 스트림 데이터를 읽고 JSON으로 변환하여 Promise로 반환하기 때문에 body는 쓰지 않아도 됩니다.

const data = fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then((res) => console.log(res.json()))
    .catch((err) => console.error(err));

 

이제 res.json()이 Promise 객체로 반환된 것을 볼 수 있습니다.

 

const data = fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then((res) => res.json())
    .then((data) => console.log(data))
    .catch((err) => console.error(err));

 

한번 더 then()을 이용하여 Promise를 풀어주면

const data = fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then((res) => res.json())
    .then((data) => console.log(data))
    .catch((err) => console.error(err));

 

 

이렇게 데이터가 출력되는 것을 볼 수 있습니다.

 

그리고 fetch를 사용할 때는 res.ok를 통하여 HTTP 상태 코드를 기반으로 성공 여부를 확인하고 예외 처리를 해줘야 합니다.

 

fetch('https://jsonplaceholder.typicode.com/invalid-endpoint')
    .then((res) => {
        if (!res.ok) {
            throw new Error(`HTTP error! Status: ${res.status}`);
        }
        return res.json();
    })
    .then((data) => console.log('Data:', data))
    .catch((err) => console.error('Error:', err));

 

fetch는 HTTP 요청이 실패(예: 404, 500)하더라도 Rejected Promise를 반환하지 않고 요청이 성공적으로 처리되어 응답이 반환되었다고 간주하고 Resolved Promise를 반환합니다. 따라서, 에러 상태 코드를 처리하지 않으면, 성공적인 요청처럼 동작할 수 있어 예상치 못한 버그를 발생시킬 수 있습니다.

 

 

이 과정만 봤을 때는 Promise 객체를 2번 풀어야 하는 fetch보다는 axios를 사용하는 것이 더 좋을 것 같은데 왜 fetch를 더 많이 사용하는 추세일까요?

별도의 설치 없이 바로 사용할 수 있기 때문에, 프로젝트의 의존성을 줄여주고 유지보수가 더 용이해집니다.

fetch가 더 최신 트렌드로 과거에는 node 환경에서 지원이 안됐지만 지원이 되는 지금은 fetch를 안 쓸 이유가 없다는...

그리고 맨 처음에 말했듯 NextJS의 Edge 환경에서도 안정적으로 동작합니다.

 

아직 NextJS를 안 배워서 그런가 잘 와닿지는 않지만 fetch에 좀 더 익숙해지도록 노력해야겠습니다....!