Axios #1

준호·2020년 11월 1일
1

1차 프로젝트때는 fetch로 backend와 통신을 했다. 2차때는 Axios 사용을 위해 미리 공부해보자.

Axios란?

브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리
크로스브라우징에 최적화 되어있다.

특징

  • 브라우저에선 - XMLHttpRequests, Nodejs에선 - https 요청을 생성한다.
  • Promise API를 지원한다
  • 요청과 응답을 차단
  • 요청과 응답 데이터를 변환한다
  • 취소 요청이 가능하다
  • JSON 데이터를 자동으로 변환한다 (JSON.stringify 필요없음)
  • 사이트 간 요청위조 보호를 위한 클라이언트 사이드를 지원한다.

설치

npm install axios

사용법

GET 요청

const axios = require('axios');

// ID로 사용자 요청
axios.get('/user?ID=12345')
  // 응답(성공)
  .then(function (response) {
    console.log(response);
  })
  // 응답(실패)
  .catch(function (error) {
    console.log(error);
  })
  // 응답(항상 실행)
  .then(function () {
    // ...
  });

4번째 줄의 axios.get은 아래와 같이 쓸 수 있다

axios.get('/user', {
    params: {
      ID: 12345
    }
  })

Async/Await

Async/Await를 사용해 비동기 통신을 요청 할 수 있다.
오류 디버깅을 위해 try...catch문을 사용한다.

async function getUser() {
  try {
    const response = await axios.get('/user?ID=12345');
    console.log(response);
  } catch (error) {
    console.error(error);
  }
}

POST 요청

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

아래와 같은 방식으로 사용 가능하다.

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

멀티 요청

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
  }));

여러개의 요청을 동시 수행하기 위해서 axios.all 메서드를 사용한다.

응답 스키마

요청에 따른 응답 결과에는 다음과 같은 정보가 담겨있다.

{
  // `data`는 서버가 제공한 응답(데이터)입니다.
  data: {},

  // `status`는 서버 응답의 HTTP 상태 코드입니다.
  status: 200,

  // `statusText`는 서버 응답으로 부터의 HTTP 상태 메시지입니다.
  statusText: 'OK',

  // `headers` 서버가 응답 한 헤더는 모든 헤더 이름이 소문자로 제공됩니다.
  headers: {},

  // `config`는 요청에 대해 `axios`에 설정된 구성(config)입니다.
  config: {},

  // `request`는 응답을 생성한 요청입니다.
  // 브라우저: XMLHttpRequest 인스턴스
  // Node.js: ClientRequest 인스턴스(리디렉션)
  request: {}
}

then으로 다음과 같이 응답을 받을 수 있다.

axios.get('/user/12345')
  .then(function (response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });
profile
빠르게 발전중인 프론트엔드 개발자

0개의 댓글