Programming/CS

HTTP 요청, Axios와 Fetch 중 어떤 걸 쓰지?

hodo- 2023. 8. 10. 23:03

네트워크 요청을 할 때 Axios, Fetch와 같은 HTTP 클라이언트를 사용한다.

Fetch는 네트워크 요청을 위해 fetch()라는 메서드를 제공하는 인터페이스로 모던 브라우저에 내장되어있어 별도의 설치가 필요없다.

Axios는 패키지 매니저를 통해 설치하여 프로젝트에 추가할 수 있다.

둘 다 promise 기반의 HTTP 클라이언트이다.


Axios  node.js환경에서 설치 방법

1. npm install axios
2. 프로젝트에서 import axios from "axios";


기능 비교

1. 문법

- Fetch

두개의 인자를 받는다.
1. 가져오고자 하는 리소스 URL
2. 요청의 설정 옵션을 포함하는 객체 (선택적 인자로 넘기지 않으면 기본 GET 요청)

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: {},
});

//HTTP 메서드 붙일 수도 있음
axios.get(url, {
  // 설정 옵션
});

2. 응답 처리 비교

JSON에서의 데이터 처리 비교

- Fetch

const url = "https://가져올 링크";

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

.then( ) 메서드에서 처리된 promise 반환 => 응답 객체의 .json() 메서드 호출

JSON형식의 데이터로 이행된 또 다른 promise 반환

따라서 보통 2개의 .then() 호출을 가짐

- Axios

const url = "https://가져올 링크";

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

응답 데이터가 기본적으로 JSON 타입이다.

응답 객체의 data 프로퍼티 사용한다.

axios.get(url, {
  responseType: "json", // options: 'arraybuffer', 'document', 'blob', 'text', 'stream'
});

위와 같이 기본 JSON 데이터 타입을 재정의 할 수도 있다.

3. 데이터 전송 POST

- Fetch

const url = "https://test.com";

const test = {
  title: "test",
  vaild: true,
};

axios
  .post(url, {
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify(test)
  })
  .then(console.log);

dJSON.stringify()를 사용하여 객체를 문자열로 변환한 후 body에 할당한다.

- Axios

데이터를 JSON 문자열로 바꿔야하는데 Axios가 자동으로 데이터를 문자열로 변환해준다

const url = "https://test";

const test = {
  title: "test",
  valid: true,
};

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

보내고자 하는 data는 data 프로퍼티에 할당함

컨텐츠 유형 헤더는 위가 기본이다.

응답 데이터는 response.data에 있다.

4. 에러 처리

둘 다 이행(resolve)되거나 거부(reject)된 promise 반환한다

거부되면 .catch()를 사용하여 에러를 처리할 수 있다.

- Axios

const url = "https://test";

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

promise는 상태코드가 2xx의 범위를 넘어가면 거부한다.

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

에러 객체의 response프로퍼티는 클라이언트가 2xx범위를 벗어나는 상태 코드를 가진 에러 응답을 받았음을 나타낸다.

에러 객체의 request 프로퍼티는 요청이 수행되었지만 클라이언트가 응답을 받지 못했음을 나타낸다

- Fetch

에러나 다른 HTTP 에러 응답을 받았다고 해서 promise를 거부하지 않는다.

네트워크 장애가 발생했을 때만 promise를 거부한다.

따라서 .then절을 사용하여 수동으로 HTTP 에러를 처리 해줘야한다.

const url = "https://test";

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

5. 응답 시간 초과 / 요청 취소

각각 HTTP 요청이 시간이 초과될 경우 어떻게 처리할까?

- Axios

timeout속성을 설정 객체에 추가하여 요청이 종료될 때까지의 시간을 밀리초로 지정할 수 있다.

const url = "https://jest";

axios
  .get(url, {
    timeout: 4000, // 기본 설정은 '0'입니다 (타임아웃 없음)
  })
  .then((response) => console.log(response.data))
  .catch((err) => {
    console.log(err.message);
  });

위는 요청이 4초 이상 걸릴 경우 종료하고 에러를 로깅하도록 하고 있다.

- Fetch

AbortController 인터페이스를 사용하여 요청을 취소할 수 있다.

const url = "https://test";

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

signal 객체를 설정 옵션을 통해 fetch()에 넘긴다.

abort 메서드가 호출될 때마다 fetch 요청이 종료된다.

setTimeout 기능을 사용하여 서버가 4초 이내 응답하지 않으면 작업이 종료된다.

6. 성능

둘 다 promise 기반이기 때문에 성능 문제를 일으키지 않는다. (비동기 처리가 가능하기 때문에 작업이 효율적임)


개인의 입맛에 따라 사용하면 될 거 같지만 나는 axios가 좀 더 간편해보여서 주로 사용할 거 같다.

'Programming > CS' 카테고리의 다른 글

REST API란? API부터 알아보자  (0) 2023.08.12