[라이브러리] axios

RingKim1·2024년 6월 12일

React

목록 보기
4/6

1. 📌axios

브라우저와 node.js에서 사용할 수 있는 Promise 기반 HTTP 클라이언트 라이브러리

axios 공식문서

  • http를 이용해서 서버와 통신하기 위해 사용하는 패키지!

2. 특징

  • Promise 기반: 비동기 요청을 처리하며, .then()과 .catch()로 성공과 실패를 관리

  • 자동 JSON 변환: 요청 및 응답 데이터를 자동으로 JSON으로 변환

  • 요청 취소: 필요 없는 요청을 쉽게 취소할 수 있는 기능

  • 인터셉터: 요청이나 응답을 가로채서 수정할 수 있는 기능

  • CSRF 보호: XSRF 토큰을 자동으로 처리하여 CSRF 공격 방지

  • 브라우저와 Node.js 지원: 클라이언트와 서버 환경 모두에서 사용 가능

  • 타입스크립트 지원: 타입 안전성을 높여 코드 가독성 향상

3. 설치

yarn add axios

npm install axios

4. 사용

4-1. 기본 사용

🌟추후 다시 정리 필요

const axios = require('axios');

// GET 요청 예제
axios.get('https://api.example.com/data') // 공부하는 차원에서 json-server 와 연결하여 사용
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error fetching data:', error);
  });

// POST 요청 예제
axios.post('https://api.example.com/data', {
    key1: 'value1',
    key2: 'value2'
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error('Error posting data:', error);
  });

4-2. 인터셉터

요청 인터셉터

axios.interceptors.request.use(config => {
  // 요청을 보내기 전에 무언가를 할 수 있음
  console.log('Request sent', config);
  return config;
}, error => {
  // 요청 에러가 발생했을 때 일을 수행
  return Promise.reject(error);
});

응답 인터셉터

axios.interceptors.response.use(response => {
  // 응답 데이터를 가공할 수 있음
  console.log('Response received', response);
  return response;
}, error => {
  // 응답 에러가 발생했을 때 일을 수행
  return Promise.reject(error);
});

요약

  • Axios는 HTTP 요청을 간편하게 처리할 수 있는 강력한 라이브러리
  • 비동기 요청, 데이터 변환, 인터셉터 등을 통해 복잡한 HTTP 통신을 쉽게 관리
profile
커피는 콜드브루

0개의 댓글