[etc] fetch 대신 axios를 써보자

exoluse·2021년 12월 10일
1

etc

목록 보기
4/16
post-thumbnail

알고는 있지만 복기해보자. axios 특징

  1. Promise API(ES6)를 활용하는 http 비동기 통신 라이브러리다.
  2. http 요청 취소가 가능하다.
  3. http 요청/응답을 json 형태로 자동 변환해준다.

axios 설치!

이번에는 npm이 아닌 cdn으로 설치해보자. 차기 프로젝트가 nodejs를 지원하지 않는 탓이다.

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

설치 끝.

사용 방법

  1. method : 요청 방식(기본값은 get)
  2. url : 요청 주소
  3. headers : 헤더 내용
  4. data : method가 put, post, patch일 떄에 body에 실려가는 데이터
  5. params : url 파라미터
  6. timeout : 타임아웃(millisecond)
  7. responseType : 서버가 응답해주는 데이터 타입(text, json 등)
axios({
    method: "get", // 통신 방식
    url: "www.naver.com", // 통신할 웹문서
    headers: {'X-Requested-With': 'XMLHttpRequest'}
    params: { api_key: "1234", langualge: "en" },
    timeout: 1000
    responseType: 'json', // default
}).then(function (response) {
    // response Action
});

응답 객체

  1. data : 서버가 리턴한 데이터
  2. status : HTTP 상태 코드
  3. statusText : HTTP 상태 메시지
  4. headers : 서버 응답 헤더값 표시
  5. config : 요청시 axios 설정
  6. request : 요청 객체
{
  data: {},
  status: 200,
  statusText: 'OK',
  headers: {},
  config: {},
  request: {}
}

0개의 댓글