axios 사용해보기

seul gi lee·2020년 1월 20일
6

axios?

Promise based HTTP client for the browser and node.js

axios는 node.js와 브라우저를 위한 http통신 javascript 라이브러리입니다.

아래와 같이 모든 브라우저를 지원합니다. (Fetch와 달리 크로스 브라우징에 최적화)

특징

  • 브라우저에선 XMLHttpRequests을 nodejs에선 http 요청 생성
  • Promise API 지원
  • 요청과 응답을 중단
  • JSON 데이터 자동 변환
  • 요청 취소
  • XSRF로부터 보호하기위한 클라이언트 측 지원

설치

npm

$ npm install axios

bower

$ bower install axios

yarn

$ yarn add axios

cdn

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

예제

GET 요청

// GET request for remote image
axios({
  method: 'get',
  url: 'http://bit.ly/2mTM3nY',
  responseType: 'stream'
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
  });

or

axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .finally(function () {
    // always executed
  }); 

POST 요청

axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});

or

axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

위의 예시와 같이 method에 요청별로 사용할 수도 있고, 명확하게 사용도 가능합니다.

참고 - https://github.com/axios/axios, https://tuhbm.github.io/2019/03/21/axios/

profile
백설 집사의 개발블로그입니다. :D

3개의 댓글

comment-user-thumbnail
2020년 4월 4일

axios 자주 쓰는 라이브러리인데 여러모로 사용하기 편하더라고요

1개의 답글