Axios이란?
프로젝트를 하면서 알게 되었던 Axios에 대해 정리를 한 내용 입니다.
주된 내용은 npmjs의 axios에 대한 내용을 번역해서 참고했습니다.
Axios이란?
Axios는 브라우저와 Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리입니다.
Promise객체는 비동기 작업이 맞이할 미래의 완료 또는 실패와 그 결과 값을 나타냅니다.
Install
Axios를 사용하기 위해선 일단 설치를 먼저 진행해야합니다.
npm을 사용한다면
$ npm install axios
yarn을 사용한다면
$ yarn add axios
CDN을 사용하고자 한다면
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
위 방식중 현재 사용하고자 하는 방식을 이용하면 됩니다.
사용법
[Get 요청]
axios를 사용해 GET 요청하는 방법은 다음과 같습니다.
GET은 서버에서 어떤 데이터를 가져와서 보여주기 위해
URL주소에 있는 쿼리스트링을 활용해서 정보를 전달합니다.
const axios = require('axios');
// ID로 사용자 요청
axios.get('/user?ID=12345')
  // 응답(성공)
  .then(function (response) {
    console.log(response);
  })
  // 응답(실패)
  .catch(function (error) {
    console.log(error);
  })
  // 응답(항상 실행)
  .then(function () {
    // ...
  });
위 방식처럼 axios.get을 이용해서 GET 요청 시 매개변수를 받을 수 있습니다.
또 다른 방식으로는 params 옵션을 이용해서 받을 수 있습니다.
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  })
  .then(function () {
    // ...
  });
[Async 함수]
async / await를 사용할 경우 함수 또는 메서드 앞에 async 키워드를 사용하고
내부에 async 키워드를 사용해 비동기 통신 요청을 처리합니다.
async / await는 오류 디버깅을 위해 try/catch 구문을 사용합니다.
async function getUser() { // async 사용
  try { // try
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) { //catch
    console.error(error);
  }
}
[POST 요청]
POST 요청도 GET 요청과 거의 같습니다.
POST 메서드의 두 번째 인자는
본문으로 보낼 데이터를 설정한 객체 리터럴을 전달합니다.
axios.post('/user', {
    firstName: 'Fred',
    lastName: 'Flintstone'
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
[멀티 요청]
여러 개의 요청을 동시 수행할 경우 axios.all() 메서드를 사용합니다.
function getUserAccount() {
  return axios.get('/user/12345');
}
function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}
axios.all([getUserAccount(), getUserPermissions()]) // <-- 이쪽
  .then(axios.spread(function (acct, perms) {
    // Both requests are now complete
  }));
API
구성(configuration) 설정을 axios()에 전달하여 요청할 수 있습니다.
이게 무슨 말인가하니 위에 있던 예제에서는 axios.get 또는 axios.post 이런식으로
작성을 해서 통신을 했다하면 아래의 예시들처럼 내부에 method 방식을 지정해서
전송을 한다는 뜻이었습니다.
[POST 방식]
// POST 요청 전송
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
[GET 방식]
// 원격 이미지 GET 요청
axios({
  method:'get',
  url:'url링크를 적어욧',
  responseType:'stream'
})
  .then(function (response) {
    response.data.pipe(fs.createWriteStream('photophoto.jpg'))
  });
HTTP 메서드 별칭
편의를 위해 지원되는 모든 요청 메소드에 별칭이 제공됩니다.
axios.get(url[, config])            // GET
axios.post(url[, data[, config]])   // POST
axios.put(url[, data[, config]])    // PUT
axios.patch(url[, data[, config]])  // PATCH
axios.delete(url[, config])         // DELETE
axios.request(config)
axios.head(url[, config])
axios.options(url[, config])
별칭 메소드를 사용하면 설정(config)에서
url, method 및 data 속성을 지정할 필요가 없습니다.
// axios() 사용 시
axios({
  url: '/user/12345',
  method: 'put',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
})
// axios.put() 별칭 메서드 사용 시
axios.put('/user/12345', {
  firstName: 'Fred',
  lastName: 'Flintstone'
})