Today I Learned/TIL 07

2023 - 07 - 17 AXIOS

sangwoo_rhie 2023. 7. 20. 17:17

오늘 배운것 : AXIOS

 

  • Axios는 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리 아다.
  • 쉽게 말해서 백엔드랑 프론트엔드랑 통신을 쉽게하기 위해 Ajax와 더불어 사용한다.
  • 이미 자바스크립트에는 fetch api가 있지만, 프레임워크에서 ajax를 구현할땐 axios를 쓰는 편이라고 보면 된다.
  • 운영 환경에 따라 브라우저의 XMLHttpRequest 객체 또는 Node.js의 http api 사용
  • Promise(ES6) API 사용
  • 요청과 응답 데이터의 변형
  • HTTP 요청 취소
  • HTTP 요청과 응답을 JSON 형태로 자동 변경

 

서버에서 axios 설치

> npm install axios

클라이언트(html)에서 axios 설치

<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

또는

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

 

axios 파라미터 문법 예시

axios({
    method: "get", // 통신 방식
    url: "www.naver.com", // 서버
    headers: {'X-Requested-With': 'XMLHttpRequest'} // 요청 헤더 설정
    params: { api_key: "1234", langualge: "en" }, // ?파라미터를 전달
    responseType: 'json', // default
    
    maxContentLength: 2000, // http 응답 내용의 max 사이즈
    validateStatus: function (status) {
      return status >= 200 && status < 300; // default
    }, // HTTP응답 상태 코드에 대해 promise의 반환 값이 resolve 또는 reject 할지 지정
    proxy: {
      host: '127.0.0.1',
      port: 9000,
      auth: {
        username: 'mikeymike',
        password: 'rapunz3l'
      }
    }, // proxy서버의 hostname과 port를 정의
    maxRedirects: 5, // node.js에서 사용되는 리다이렉트 최대치를 지정
    httpsAgent: new https.Agent({ keepAlive: true }), // node.js에서 https를 요청을 할때 사용자 정의 agent를 정의
})
.then(function (response) {
    // response Action
});

 

 

Axios 응답 (response)데이터

axios({
    method: "get", // 통신 방식
    url: "www.naver.com", // 서버
})
.then(function(response) {
  console.log(response.data)
  console.log(response.status)
  console.log(response.statusText)
  console.log(response.headers)
  console.log(response.config)
})

Axios 단축 메소드

axios를 편리하게 사용하기 위해 모든 요청 메소드는 aliases가 제공된다.

위 처럼 객체 옵션을 이것저것 주면 가독성이 떨어지고 너저분하니, 함수형으로 재구성하여 나눠논 것으로 이해하면 된다.

axios의 Request method에는 대표적으로 다음과 같은 것들이 있다.

  • GET : axios.get(url[, config])
  • POST : axios.post(url, data[, config])
  • PUT : axios.put(url, data[, config])
  • DELETE : axios.delete(url[, config])

 

 

 

출처

https://inpa.tistory.com/entry/AXIOS-%F0%9F%93추%9A-%EC%84%A4%EC%B9%98-%EC%82%AC%EC%9A%A9#thankYou

 

📚 AXIOS 설치 & 특징 & 문법 💯 정리

Axios 라이브러리 Axios는 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리 아다. 쉽게 말해서 백엔드랑 프론트엔드랑 통신을 쉽게하기 위해 Ajax와 더불어 사용한다. 이미

inpa.tistory.com