happy coding

[js] axios 탐방 - 1 본문

self study/library

[js] axios 탐방 - 1

yeoonii 2024. 3. 12. 22:56

1. axios란

node.js와 브라우저를 위한 Promise 기반 HTTP 클라이언트 > 동형(동일한 코드베이스로 브라우저와 node.js에서 실행이 가능하다.)

서버 사이드에서는 네이티브 node.js의 http 모듈을 사용하고, 클라이언트(브라우저)에서는 XMLHttpRequests를 사용한다.

 

2. axios 특징

  • 브라우저를 위해 XMLHttpRequests 생성
  • node.js를 위해 http 요청 생성
  • Promise API를 지원
  • 요청 및 응답 인터셉트
  • 요청 및 응답 데이터 변환
  • 요청 취소
  • JSON 데이터 자동 변환
  • XSRF를 막기위한 클라이언트 사이드 지원

3. CommonJS 사용법

const axios = require('axios').default;

 

const axios = require('axios');

// 지정된 ID를 가진 유저에 대한 요청
axios.get('/user?ID=12345')
  .then(function (response) {
    // 성공 핸들링
    console.log(response);
  })
  .catch(function (error) {
    // 에러 핸들링
    console.log(error);
  })
  .finally(function () {
    // 항상 실행되는 영역
  });

// 선택적으로 위의 요청은 다음과 같이 수행될 수 있습니다.
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
    // 항상 실행되는 영역
  });  

// async/await 사용을 원한다면, 함수 외부에 `async` 키워드를 추가하세요.
async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

typescript도 익숙하지 않지만 axios 라이브러리를 읽어보면서 익숙해져봐야겠다.

'self study > library' 카테고리의 다른 글

[js] postgreSQL - ... (spread Operator)  (0) 2024.04.13
[js] axios 탐방 - 2  (0) 2024.03.14
Comments