CodeGym /행동 /Frontend SELF KO /Axios와 Fetch

Axios와 Fetch

Frontend SELF KO
레벨 44 , 레슨 0
사용 가능

5.1 Fetch API

JavaScript에서 HTTP 요청을 수행하기 위해 두 가지 라이브러리가 자주 사용돼: 내장 함수 fetch 와 외부 라이브러리 Axios. 둘 다 API 및 기타 웹 리소스와 상호 작용하기 위한 강력하고 유연한 기능을 제공해.

Fetch API는 브라우저에 내장된 HTTP 요청을 수행하는 방법이야. 이건 promise에 기반을 두고 있으며 네트워크 요청 작업에 유연하고 현대적인 방법을 제공해.

간단한 fetch 요청의 문법:

    
      let promise = fetch(url, {method, headers,
        body})
    
  

Fetch의 주요 개념:

  • fetch(url, options): HTTP 요청을 수행하는 주요 메소드.
  • Response 객체로 해결되는 프로미스를 반환해.

Fetch를 사용한 간단한 GET 요청의 예:

JavaScript
    
      fetch('https://jsonplaceholder.typicode.com/posts/1')
        .then(response => {
          if (!response.ok) {
            throw new Error('네트워크 오류: 서버에서 잘못된 응답 수신');
          }
          return response.json();
        })
        .then(data => {
          console.log(data);
        })
        .catch(error => {
          console.error('요청 수행 중 오류: ', error);
        });
    
  

Fetch를 사용한 POST 요청 예제:

JavaScript
    
      fetch('https://jsonplaceholder.typicode.com/posts', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json'
        },
        body: JSON.stringify({
          title: 'foo',
          body: 'bar',
          userId: 1
        })
      })
        .then(response => response.json())
        .then(data => {
          console.log(data);
        })
        .catch(error => {
          console.error('요청 수행 중 오류: ', error);
        });
    
  

Fetch 설정

Fetch API는 options 객체를 통해 메소드, 헤더, 요청 본문 등 다양한 요청 매개변수를 설정할 수 있어.

JavaScript
    
      const options = {
        method: 'GET', // 또는 'POST', 'PUT', 'DELETE' 등
        headers: {
          'Content-Type': 'application/json'
        },
        // body: JSON.stringify(data) // POST 및 PUT 요청에 사용
      };

      fetch('https://jsonplaceholder.typicode.com/posts/1', options)
        .then(response => response.json())
        .then(data => console.log(data))
        .catch(error => console.error('요청 수행 중 오류: ', error));
    
  

5.2 Axios 라이브러리

Axios는 JavaScript에서 HTTP 요청을 수행하기 위해 인기 있는 라이브러리야. 기본 Fetch API에 비해 더 편리하고 기능적인 API를 제공하고, 자동 JSON 변환, 타임아웃 처리, 요청 중단 및 오래된 브라우저 지원과 같은 많은 추가 기능을 지원해.

Axios 설치

Axios는 npm을 통해 설치하거나 CDN을 통해 연결할 수 있어.

npm을 통한 설치:

Terminal
    
      npm install axios
    
  

Node.js에서 또는 모듈 번들러(예: Webpack)를 사용할 때 연결하기:

JavaScript
    
      // CommonJS의 경우
      const axios = require('axios');

      // ES6 모듈의 경우
      import axios from 'axios';
    
  

브라우저에서 CDN을 통한 연결:

HTML
    
      <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    
  

간단한 GET 요청 문법:

    
      let promise = axios.get(url)
    
  

간단한 POST 요청 문법:

    
      let promise = axios.post(url, data, config)
    
  

Axios의 주요 개념:

  • axios(config): HTTP 요청을 수행하는 주요 메소드.
  • 구성 객체를 받아들이며, url, method, headers, data 및 기타 매개변수를 포함할 수 있어.
  • 쇼트컷 메소드: Axios는 각 HTTP 메소드에 대한 메소드를 제공(axios.get, axios.post, axios.put, axios.delete 등)하여 해당 요청을 쉽게 수행할 수 있도록 해.
  • Promises: Axios의 모든 메소드는 Promise(프로미스)를 반환하며, 응답 객체로 해결되거나 오류 발생 시 거부돼.

응답 및 오류 처리가 포함된 간단한 GET 요청 문법:

JavaScript
    
      axios.get(url)
        .then(response => {
          // 성공적인 응답 처리
        })
        .catch(error => {
          // 오류 처리
        });
    
  

응답 및 오류 처리가 포함된 간단한 POST 요청 문법:

JavaScript
    
      axios.post(url, data, config)
        .then(response => {
          // 성공적인 응답 처리
        })
        .catch(error => {
          // 오류 처리
        });
    
  

Axios를 사용한 간단한 GET 요청의 예:

HTML
    
      <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    
  
JavaScript
    
      axios.get('https://jsonplaceholder.typicode.com/posts/1')
        .then(response => {
          console.log(response.data);
        })
        .catch(error => {
          console.error('요청 수행 중 오류: ', error);
        });
    
  

Axios를 사용한 POST 요청의 예:

HTML
    
      <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    
  
JavaScript
    
      axios.post('https://jsonplaceholder.typicode.com/posts', {
          title: 'foo',
          body: 'bar',
          userId: 1
        })
        .then(response => {
          console.log(response.data);
        })
        .catch(error => {
          console.error('요청 수행 중 오류: ', error);
        });
    
  

5.3 Axios 구성

Axios 설정

Axios는 config 객체를 통해 HTTP 요청을 구성할 수 있는 기능을 제공하며, 이 객체는 url, method, headers 및 데이터(data)와 같은 매개변수를 포함해. 아래는 요청 구성을 위한 기본 예제야:

HTML
    
      <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    
  
JavaScript
    
      const config = {
        method: 'get', // 'get', 'post', 'put', 'delete' 등일 수도 있어
        url: 'https://jsonplaceholder.typicode.com/posts/1',
        headers: {
          'Content-Type': 'application/json' // 데이터 타입을 지정하기 위한 헤더
        },
        // data: JSON.stringify(data) // 요청 본문을 전달하기 위한 POST 및 PUT 요청에 사용
      };

      axios(config)
        .then(response => console.log(response.data))
        .catch(error => console.error('요청 수행 중 오류: ', error));
    
  

Axios의 추가 기능:

  1. 요청 매개변수: URL에 요청 매개변수를 전달할 수 있어.
  2. 요청 중단: AbortController를 사용해.
  3. 타임아웃: 요청 일정 시간을 설정할 수 있어.

요청 매개변수 사용 예제:

HTML
    
      <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    
  
JavaScript
    
      axios.get('https://jsonplaceholder.typicode.com/posts', {
        params: {
          userId: 1 // 요청 매개변수는 params 객체를 통해 전달돼
        }
      })
        .then(response => {
          console.log(response.data);
        })
        .catch(error => {
          console.error('요청 수행 중 오류: ', error);
        });
    
  

5.4 Fetch와 Axios 비교

이제 중요한 포인트에서 Fetch와 Axios를 비교해 보자:

1. 사용의 간편함:

  • Fetch: 기본 작업에 사용하는 게 쉽지만, 복잡한 시나리오(예: JSON 변환, 타임아웃 처리)에 추가 처리가 필요해.
  • Axios: 복잡한 요청을 수행하기에 더 편리하고 강력한 API를 제공해.

2. JSON 지원:

  • Fetch: 응답 본문을 JSON으로 변환하기 위해 명시적 response.json() 호출이 필요해.
  • Axios: JSON 응답을 자동으로 변환해 줘.

3. 타임아웃:

  • Fetch: 타임아웃에 대한 내장 지원이 없어. 타임아웃 구현을 위해 AbortController나 래퍼를 사용해야 해.
  • Axios: 구성에서 타임아웃을 설정할 수 있어.

4. 인터셉터:

  • Fetch: 요청 및 응답 인터셉터를 지원하지 않아.
  • Axios: 요청을 보내기 전과 응답을 받은 후에 로직을 수행하기 위해 인터셉터를 사용할 수 있어.

Axios 인터셉터 예제

Interceptors (인터셉터)는 요청을 보내기 전이나 응답을 받은 후에 특정 작업을 수행할 수 있어:

HTML
    
      <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    
  
JavaScript
    
      // 요청용 인터셉터 추가
      axios.interceptors.request.use(config => {
        console.log('서버에 요청이 전송되었어: ', new Date());
        return config;
      }, error => {
        return Promise.reject(error);
      });

      // 응답용 인터셉터 추가
      axios.interceptors.response.use(response => {
        console.log('서버로부터 응답을 받았어: ', new Date());
        return response;
      }, error => {
        return Promise.reject(error);
      });

      // 인터셉터를 사용한 요청 예제
      axios.get('https://jsonplaceholder.typicode.com/todos/1')
        .then(response => console.log(response.data))
        .catch(error => console.error('요청 수행 중 오류: ', error));
    
  

Axios를 사용한 병렬 요청

Axios를 사용하면 Promise.all()을 통해 병렬 요청을 쉽게 수행하고 결과를 처리할 수 있어:

HTML
    
      <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
    
  
JavaScript
    
      Promise.all([
        axios.get('https://jsonplaceholder.typicode.com/todos/1'),
        axios.get('https://jsonplaceholder.typicode.com/todos/2')
      ])
      .then(responses => {
        responses.forEach(response => {
          console.log(response.data);
        });
      })
      .catch(error => console.error('요청 수행 중 오류: ', error));
    
  
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION