1 minute read

axios

브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리이다.

기능

브라우저 환경에서 XMLHttpRequests 요청 생성 Node.js 환경에서 http 요청 생성 Promise API 지원 요청/응답 차단(intercept) 요청/응답 데이터 변환 취소 요청 JSON 데이터 자동 변환 사이트 간 요청 위조(XSRF) 보호를 위한 클라이언트 사이즈 지원

지원하는 브라우저

Chrome | Firefox | Safari | Opera | Edge | IE | — | — | — | — | — | — | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | Latest ✔ | 11 ✔ |

사용

사용하기 위해 우선 설치를 해야한다.

$ npm install axios
# 또는 yarn add axios

다양한 method로 간단한 사용이 가능하다.

axios.get(url[, config])            // get의 경우(불러오기)
axios.post(url[, data[, config]])   // post의 경우(입력하기)
axios.patch(url[, data[, config]])  // patch의 경우(수정하기)
axios.delete(url[, config])         // delete의 경우(삭제하기)

HTTP Methods

GET 요청

const axios = require('axios');


axios.get('/user?ID=12345')  // /user?ID=12345앤드포인트로 get요청을 보냄
.then(function (res) {       // 요청에 성공했을 때 
  console.log(res);
})
.catch(function (err) {      // 통신 에러로 요청에 실패했을 때
  console.log(err);
})
.then(function () {          // 항상 실행

})

// 혹은 아래와 같이 수행 가능

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

POST 요청

axios.post('/user', {
  firstName: 'Mimi',
  lastName: 'Cho'
})
.then(function (res){
  console.log(res);
})
.catch(function (err){
  console.log(err);
})

여러개의 요청도 처리 가능하다

function getUserAccount() {
  return axios.get('/user/12345');
}

function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}

Promise.all([getUserAccount(), getUserPermissions()])
  .then(function (results) {
    const acct = results[0];
    const perm = results[1];
  });

참고링크

Axios 공식문서