본문 바로가기

Web Sever 개발과 CS 기초/JS 프론트엔드

Javascript Axios 사용 방법

관련 내용

해당 프로젝트 깃허브

개요 목적

Spring Rest API 백엔드 서버를 테스트하는 두 가지 방법이 있다.

첫 번째는 서버가 단순할 때 Postman으로 테스트한다.

그러나, 복잡한 백엔드 서버일 때는 Postman으로 일일이 테스트하는 것은 너무 번거롭다.

두 번째 방법인 UI 웹페이지를 만들고 Axios를 사용해 RestAPI 서버를 테스트 한다.

Axios 특징

  • Axios는 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리
  • 운영 환경에 따라 브라우저의 XMLHttpRequest 객체 또는 Node.js의 http api 사용
  • Promise(ES6) API 사용
  • HTTP 요청과 응답을 JSON 형태로 자동 변경

Axios 사용하여 백엔드 서버와 통신하기

GET 데이터 정보 가져오기

get method와 requestParameter를 보내서 백엔드 서버 음식 데이터를 받아보자.

코드 위치 SeperateDeliveryService\UIDeliveryService\src\main\resources\templates\company\food\updatePriceForm.html

//html에 해당 script을 붙여 넣어 axios 통신을 할 수 있다.
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<script th:inline="javascript">
    window.onload = function () {
			
      //핵심!!!
      //axios 시작
      //url, method, parameter 정보를 입력한다.
      axios({
        url: "http://127.0.0.1:5510/api/delivery-service/company/food/information",
        method: 'get',
        params: {
          foodId: 3
        }
      })
      //요청이 성공 햇을 경우,
      //.then(funtion (response) { 안에
      //원하는 동작을 작성한다. 
      .then(function (response) {
				let idInput = document.getElementById("id");
        idInput.value = response.data.companyFoodDto.name;
      })
      //통신 실패 상황 시
      //.catch(funtion(error) { 안에
      //원하는 동작을 작성한다.
      .catch(function (error) {
        console.log(error);
      });
    }
  </script>

주의 사항,

get method는 requestBody를 첨부할 수 없다.

PUT 데이터 추가, 수정하기

button을 클릭하면, put 메소드와 request body를 보내 음식 가격을 수정해보자.

코드 위치 SeperateDeliveryService\UIDeliveryService\src\main\resources\templates\company\food\updatePriceForm.html

<script th:inline="javascript">
    btnSubmit.onclick = function () {
        axios({
          url: "<http://127.0.0.1:5510/api/delivery-service/company/food/update>",
          method: 'put',
          //핵심!!!
          //data 안에 json 형식으로 보낼 리퀘스트 바디를 입력한다.
          data: {
            foodId: foodId,
            price: priceInput.value
          }
        })
        .then(function (response) {
          if (status == 200) {
            alert("음식 가격 변경에 성공했습니다.")
            window.location.href = referrer;
          }
        })
        .catch(function (error) {
          console.log(error)
        })
      };
  </script>

<동작 확인 하기>

put, get외에도 delete, post, patch 메소드를 사용할 수 있다.


Reference

https://velog.io/@zofqofhtltm8015/Axios-사용법-서버-통신-해보기

(공식 문서)

https://github.com/axios/axios#axios-api