[React] Axios


01

Axios

Axios는 HTTP 클라이언트 라이브러리로, JavaScript에서 API 호출을 쉽게 할 수 있도록 도와주는 라이브러리입니다. Promise 기반으로 작동하며, 브라우저와 Node.js에서 모두 사용할 수 있습니다. 특히, React에서 자주 사용됩니다.

 

📌 Axios 설치

//npm을 사용하는 경우
npm install axios

//yarn을 사용하는 경우
yarn add axios

02

기본 사용법

Axios는 GET, POST, PUT, DELETE와 같은 HTTP 메서드를 사용하여 API 요청을 보낼 수 있습니다.

다음은 가장 기본적인 예시입니다.

 GET 요청 예시

서버에서 데이터를 가져오는 예시입니다.

import axios from "axios";

axios.get("https://jsonplaceholder.typicode.com/users")
  .then(response => {
    console.log(response.data); // 서버에서 받은 데이터 출력
  })
  .catch(error => {
    console.error("Error:", error);
  });

 

✅ POST 요청 예시

서버에 데이터를 보내는 예시입니다.

import axios from "axios";

const newUser = {
  name: "John Doe",
  email: "johndoe@example.com"
};

axios.post("https://jsonplaceholder.typicode.com/users", newUser)
  .then(response => {
    console.log(response.data); // 서버에서 응답한 데이터 출력
  })
  .catch(error => {
    console.error("Error:", error);
  });

03

axios.create()로 인스턴스 설정

위에서 언급한 것처럼, axios.create()를 사용하여 기본 설정을 할 수 있습니다.

예를 들어, 기본 URL을 설정하여 매번 URL을 입력하지 않도록 할 수 있습니다.

import axios from "axios";

const axiosInstance = axios.create({
  baseURL: "https://jsonplaceholder.typicode.com", // 기본 URL 설정
  headers: {
    "Content-Type": "application/json", // 기본 헤더 설정
  }
});

axiosInstance.get("/users")
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error("Error:", error);
  });

04

요청 취소

Axios는 요청을 취소할 수 있는 기능도 제공합니다.

예를 들어, 사용자가 요청을 보내고 몇 초 뒤에 그만두면, 그 요청을 취소할 수 있습니다.

import axios from "axios";
import { CancelToken } from "axios";

const source = CancelToken.source();

axios.get("https://jsonplaceholder.typicode.com/users", {
  cancelToken: source.token
})
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (axios.isCancel(error)) {
      console.log("Request canceled:", error.message);
    } else {
      console.error("Error:", error);
    }
  });

// 요청을 취소하려면
source.cancel("Operation canceled by the user.");

05

응답 처리

Axios는 응답 데이터를 자동으로 JSON 형식으로 파싱해 주며, 여러 응답 속성들을 제공합니다.

예를 들어, status, data, headers 등을 확인할 수 있습니다.

axios.get("https://jsonplaceholder.typicode.com/users")
  .then(response => {
    console.log("Status:", response.status); // 상태 코드
    console.log("Data:", response.data); // 실제 데이터
    console.log("Headers:", response.headers); // 응답 헤더
  })
  .catch(error => {
    console.error("Error:", error);
  });

06

오류 처리

Axios는 응답 오류  네트워크 오류를 모두 처리할 수 있습니다. 오류를 catch를 사용하여 처리합니다.

axios.get("https://jsonplaceholder.typicode.com/invalid-endpoint")
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    if (error.response) {
      // 서버가 응답을 했지만 상태 코드가 2xx가 아닌 경우
      console.error("Response error:", error.response.status);
    } else if (error.request) {
      // 요청은 성공적으로 이루어졌지만 응답을 받지 못한 경우
      console.error("Request error:", error.request);
    } else {
      // 오류 발생 시의 설정
      console.error("Error:", error.message);
    }
  });

07

번외: fetch와 axios의 차이점

두 가지 모두 비동기 방식으로 데이터를 처리하고, Promise 기반으로 동작하기 때문에 기본적인 구조는 유사합니다.

그러나 몇 가지 차이점이 있습니다.

  fetch axios
응답 처리 응답 데이터를 수동으로 JSON으로 변환해야 합니다.
예: response.json()
응답을 자동으로 JSON 형식으로 변환해줍니다.
에러 처리 HTTP 상태 코드가 200~299일 때만 성공으로 간주하고, 그 외의 상태 코드는 에러를 처리해야 합니다. HTTP 상태 코드가 200~299일 때만 성공으로 간주하고, 나머지 상태 코드는 자동으로 에러로 처리됩니다.
설정 설정을 위해 매번 headersbody를 명시적으로 설정해야 합니다. 기본적으로 타입 설정, 헤더, 쿼리 파라미터 등을 좀 더 간편하게 설정할 수 있습니다.

08

마무리

이번 포스팅에서는 Axios를 사용하여 React 환경에서 API 호출을 하는 방법을 알아보았습니다.

Axios는 Promise 기반의 HTTP 클라이언트로, 데이터를 서버와 주고받을 때 매우 유용하게 사용할 수 있습니다.

 

특히, GET, POST, PUT, DELETE 등 다양한 HTTP 메서드를 지원하며, 비동기 처리 오류 처리도 간편하게 할 수 있습니다.

 

✅ Axios의 주요 장점 정리

  • 간편한 사용법: axios.get(), axios.post()와 같은 메서드를 통해 직관적으로 API를 호출할 수 있습니다.
  • 자동 JSON 변환: 응답 데이터를 자동으로 JSON 형식으로 변환해 줍니다.
  • 인스턴스 설정: axios.create()를 통해 baseURL이나 기본 헤더를 설정하면, API 요청을 더욱 효율적으로 관리할 수 있습니다.
  • 오류 처리: catch 블록을 통해 서버 오류, 네트워크 오류 등을 쉽게 처리할 수 있습니다.
  • 요청 취소 기능: CancelToken을 이용해 불필요한 API 요청을 취소할 수 있습니다.

 

✅ Axios를 활용할 때의 팁

  • 전역 인스턴스 사용: 프로젝트 초기 설정 시, axiosInstance를 만들어 사용하는 것이 좋습니다. 이를 통해 중복 코드를 줄이고, API 요청의 일관성을 유지할 수 있습니다.
  • 에러 메시지 처리: response, request, message를 통해 다양한 오류 상황을 처리할 수 있습니다.
  • React와의 통합: useEffect 훅과 함께 사용하면, 컴포넌트 렌더링 시 API 호출을 쉽게 구현할 수 있습니다.