3 분 소요

2022. 08. 04. 수업내용 정리

axios 간단 정리


  • axios

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

    백엔드랑 프론트엔드의 통신을 쉽게하기 위해 Ajax와 함께 사용합니다.

    이미 자바스크립트에 fetch API가 있지만, 프레임워크에서 ajax를 구현할 땐 axios를 쓰는 편입니다.



    • 특징

      • 운영 환경에 따라 브라우저의 XMLHttpRequest 객체 또는 Node.js의 http api 사용

      • Promise(ES6) API 사용

      • 요청과 응답 데이터의 변형

      • HTTP 요청 취소

      • HTTP 요청과 응답을 JSON 형태로 자동 변경



    • 사용법(서버 기준, cmd.. terminal..)

      npm install axios

    axios({
        method: "get", // 통신 방식
        url: "www.naver.com", // 서버
        headers: {'X-Requested-With': 'XMLHttpRequest'} // 요청 헤더 설정
        params: { api_key: "1234", langualge: "en" }, // ?파라미터를 전달
        responseType: 'json', // default
          
         
        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
    });
    

    - method : 요청방식 (defalut:GET)

    - url : 서버 주소

    - headers : 요청 헤더

    - data : 요청 방식이 ‘PUT’, ‘POST’, ‘PATCH’ 해당하는 경우 body에 보내는 데이터

    - params : URL 파라미터 (key=value 로 요청하는 url get 방식을 객체로 표현한 것)

    - responseType : 서버가 응답해주는 데이터의 타입 지정 (arraybuffer, document, json, stream, blob)

    - withCredentials : cross-site access-control 요청을 헝용 유무. 이를 true로 할 시 cross-origin으로 쿠키값을 전달할 수 있습니다.

    • 단축 메소드

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

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

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

      - GET: axios.get(url[, config])

      - POST: axios.get(url,data[, config])

      - PUT: axios.get(url,data[, config])

      - DELETE: axios.get(url[, config])

      axios.request(config)
           
      axios.get(url[, config])
           
      axios.delete(url[, config])
           
      axios.head(url[, config])
           
      axios.options(url[, config])
           
      axios.post(url[, data[, config]])
           
      axios.put(url[, data[, config]])
           
      axios.patch(url[, data[, config]]) 
      


      1. axos GET

        단순 데이터(페이지 요청, 지정된 요청) 요청을 수행할 경우와 파라미터 데이터를 포함시키는 경우(사용자 번호에 따른 조회)에 사용합니다.

        const axios = require('axios'); // node.js쓸때 모듈 불러오기
                
                
        // user에게 할당된 id 값과 함께 요청을 합니다.
        axios.get('/user?ID=12345')
          .then(function (response) {
            // 성공했을 때
            console.log(response);
          })
          .catch(function (error) {
            // 에러가 났을 때
            console.log(error);
          })
          .finally(function () {
            // 항상 실행되는 함수
          });
                
                
        // 위와는 같지만, 옵션을 주고자 할 때는 이렇게 요청을 합니다.
        axios.get('/user', {
            params: {
              ID: 12345
            }
          })
          .then(function (response) {
            console.log(response);
          })
          .catch(function (error) {
            console.log(error);
          })
          .finally(function () {
            // always executed
          });  
                
                
        // async/await 를 쓰고 싶다면 async 함수/메소드를 만듭니다. 
        async function getUser() {
          try {
            const response = await axios.get('/user?ID=12345');
            console.log(response);
          } catch (error) {
            console.error(error);
          }
        }
        


      2. axios POST

        post 메서드에는 일반적으로 데이터를 Message Body에 포함시켜 보냅니다.

        우에서 봤던 get 메서드에서 params를 사용한 경우와 비슷하게 수행됩니다.

        axios.post("url", {
        		firstName: 'Fred',
        		lastName: 'Flintstone'
            })
            .then(function (response) {
                // response  
            }).catch(function (error) {
                // 오류발생시 실행
            })
        


      3. axios Delete

        일반적으로 body가 비어있습니다.

        REST 기반 API 프로그램에서 데이터베이스에 저장되어 있는 내용을 삭제하는 목적으로 사용합니다.

        axios.delete('/user?ID=12345')
          .then(function (response) {
            // handle success
            console.log(response);
          })
          .catch(function (error) {
            // handle error
            console.log(error);
          })
        

        하지만 query 나 params가 많아져서 헤더에 많은 정보를 담을 수 없을 때는 다음과 같이 두 번째 인자에 data를 추가해줄 수 있습니다.

        axios.delete('/user?ID=12345',{
            data: {
              post_id: 1,
              comment_id: 13,
              username: "foo"
            }
          })
          .then(function (response) {
            // handle success
            console.log(response);
          })
          .catch(function (error) {
            // handle error
            console.log(error);
          })
        


      4. axios PUT

        REST 기반 API 프로그램에서 데이터베이스에 저장되어 있는 내용을 갱신(수정) 하는 목적으로 사용됩니다.

        서버에 있는 데이터베이스의 니용을 변경하는 것을 주 목적으로 하고 있습니다.

        서버 내부적으로 GET -> POST 과정을 거치기 때문에 post 메서드와 비슷한 형태입니다.

        axios.put("url", {
                username: "",
                password: ""
            })
            .then(function (response) {
                 // response  
            }).catch(function (error) {
                // 오류발생시 실행
            })
        

댓글남기기