[React] axios

박감자·2024년 11월 26일
0

강의를 보다 잠깐 눈을 뜨면 1시간이 지나있는 것에 대하여

Axios

비동기 통신 라이브러리인 axios

Axios란?

  • Axios는 비동기 HTTP 요청을 처리하기 위한 JavaScript 라이브러리이다.
  • 특징:
    • Promise 기반으로 작동.
    • Fetch API보다 간결하며 더 많은 기능 제공.
    • 요청 및 응답 인터셉터 기능 지원.
    • 브라우저와 Node.js 환경에서 모두 사용 가능.

예시 Axios GET 요청

  • React 컴포넌트에서 axios를 사용해 GET 요청을 처리하는 방법

  • 예제 코드:

    import axios from "axios";
    import { useEffect, useState } from "react";
    
    const App = () => {
      const [posts, setPosts] = useState([]);
    
      useEffect(() => {
        axios.get("http://localhost:3000/posts")
          .then((response) => {
            setPosts(response.data);
          })
          .catch((error) => {
            console.error("Error fetching data: ", error);
          });
      }, []);
    
      return (
        <div>
          {posts.map((post) => (
            <div key={post.id}>
              <h2>{post.title}</h2>
              <p>{post.content}</p>
            </div>
          ))}
        </div>
      );
    };
    
    export default App;

Axios vs Fetch 비교

  • Axios 장점:
    • 간결한 코드.
    • 기본 설정 (Base URL, Headers) 제공.
    • 요청/응답 인터셉터 기능으로 전역 에러 처리 가능.
  • Fetch 단점:
    • 기본적으로 에러 처리가 부족하여 추가 작업 필요.
    • 사용하기 위해 더 많은 코드 작성 요구.

Axios 커스텀 인스턴스

  • 커스텀 인스턴스란?

    • axios의 기본 설정을 재사용하기 위해 생성하는 인스턴스
    • 기본 URL, 헤더 등을 설정하여 코드의 중복을 줄이고 유지보수를 용이하게 한다
  • 커스텀 인스턴스 생성 방법

    • axios.create() 메서드를 사용하여 인스턴스를 생성

    • 예시:

      import axios from 'axios';
      
      const api = axios.create({
        baseURL: 'https://api.example.com',
        timeout: 1000,
        headers: {'X-Custom-Header': 'foobar'}
      });

Axios 인터셉터의 개념과 필요성

  • 인터셉터란?

    • 요청이나 응답이 처리되기 전에 가로채서 특정 작업을 수행할 수 있는 기능
    • 예를 들어, 모든 요청에 인증 토큰을 추가하거나, 응답 에러를 일괄 처리하는 데 사용
  • 인터셉터 설정 방법

    • 요청 인터셉터:
      api.interceptors.request.use(function (config) {
        // 요청을 보내기 전에 수행할 작업
        return config;
      }, function (error) {
        // 요청 에러가 발생했을 때 수행할 작업
        return Promise.reject(error);
      });
    • 응답 인터셉터:
      api.interceptors.response.use(function (response) {
        // 응답 데이터를 가공하거나 로깅
        return response;
      }, function (error) {
        // 응답 에러가 발생했을 때 수행할 작업
        return Promise.reject(error);
      });
  • 인터셉터 활용 예시

    • 모든 요청에 인증 토큰 추가:
      api.interceptors.request.use(function (config) {
        const token = store.getState().auth.token;
        if (token) {
          config.headers.Authorization = `Bearer ${token}`;
        }
        return config;
      }, function (error) {
        return Promise.reject(error);
      });
    • 응답 에러 일괄 처리:
      api.interceptors.response.use(function (response) {
        return response;
      }, function (error) {
        if (error.response.status === 401) {
          // 인증 에러 처리
        }
        return Promise.reject(error);
      });
profile
코딩하는 감자

0개의 댓글