프로젝트 구조 변화:

  1. 프로젝트 초기화: 프로젝트 루트 디렉토리에서 npm을 초기화합니다.

    npm init
    
  2. axios 설치: axios를 프로젝트에 추가합니다.

    npm install axios
    
  3. 폴더 구조 예시: 프로젝트 폴더 구조는 다음과 같이 변할 수 있습니다.

    /your_project
    ├── src
    │   ├── main
    │   │   └── webapp
    │   │       ├── WEB-INF
    │   │       │   └── views
    │   │       │       ├── index.jsp
    │   │       │       └── other.jsp
    │   │       ├── resources
    │   │       │   └── static
    │   │       │       └── js
    │   │       │           ├── axiosModule.js
    │   │       │           └── otherJsFile.js
    └── package.json
    
    

axios 모듈화

axiosModule.js:

// axiosModule.js
import axios from 'axios';

const sendRequest = async (method, url, headers = {}, body = null) => {
  try {
    const response = await axios({
      method,
      url,
      headers,
      data: body,
    });
    return response.data;
  } catch (error) {
    throw error;
  }
};

export const get = async (url, headers = {}) => sendRequest('GET', url, headers);

export const post = async (url, headers = {}, body = null) => sendRequest('POST', url, headers, body);

export const put = async (url, headers = {}, body = null) => sendRequest('PUT', url, headers, body);

export const del = async (url, headers = {}, body = null) => sendRequest('DELETE', url, headers, body);

사용:

<!DOCTYPE html>
<html xmlns:th="<http://www.thymeleaf.org>">
<head>
    <meta charset="UTF-8">
    <title>Thymeleaf Axios 예시</title>
    <!-- axiosModule.js 로드 -->
    <script src="${pageContext.request.contextPath}/static/js/axiosModule.js" defer></script>
</head>
<body>

<!-- Thymeleaf를 사용하여 데이터 바인딩 예시 -->
<div th:id="result-container"></div>

<script>
    // Thymeleaf에서 axiosModule.js 사용 예시
    document.addEventListener('DOMContentLoaded', async function () {
        try {
            // GET 요청
            const getData = await axiosModule.get('/api/data');
            document.getElementById('result-container').innerText = 'GET 요청 결과: ' + JSON.stringify(getData);

            // POST 요청
            const postData = await axiosModule.post('/api/create', { 'Authorization': 'Bearer Token' }, { key: 'value' });
            console.log('POST 요청 결과:', postData);
        } catch (error) {
            console.error('에러 발생:', error);
        }
    });
</script>

</body>
</html>

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>My JSP Page</title>
    <script src="${pageContext.request.contextPath}/static/js/axiosModule.js" defer></script>
    <script>
        // GET 요청 예시
        axiosModule.get('/api/data')
          .then(response => {
            console.log('GET 요청 결과:', response);
          })
          .catch(error => {
            console.error('에러 발생:', error);
          });

        // POST 요청 예시
        const postData = { key: 'value' };
        axiosModule.post('/api/create', {}, postData)
          .then(response => {
            console.log('POST 요청 결과:', response);
          })
          .catch(error => {
            console.error('에러 발생:', error);
          });

        // PUT 요청 예시
        const putData = { updatedKey: 'updatedValue' };
        axiosModule.put('/api/update/1', {}, putData)
          .then(response => {
            console.log('PUT 요청 결과:', response);
          })
          .catch(error => {
            console.error('에러 발생:', error);
          });

        // DELETE 요청 예시
        axiosModule.del('/api/delete/1')
          .then(response => {
            console.log('DELETE 요청 결과:', response);
          })
          .catch(error => {
            console.error('에러 발생:', error);
          });
    </script>
</head>
<body>
    <!-- JSP 페이지 내용 -->
</body>
</html>

위의 예시에서는 axiosModule.js 파일을 가져와 각 요청 방식(GET, POST, PUT, DELETE)에 대한 함수를 사용하는 예시를 보여줍니다. 이렇게 모듈화된 axios를 사용하면 코드의 재사용성과 유지보수성이 향상됩니다.

  1. Promise 기반:
  2. 브라우저와 Node.js에서 동작:
  3. 자동 JSON 변환:
  4. 에러 처리가 쉽고 일관성 있음:
  5. 취소 요청 기능:
  6. Interceptor 지원:

ajax는 오래된 기술이며, 여전히 사용되지만 axios는 이러한 측면에서 더 풍부하고 현대적인 기능을 제공하여 개발자에게 더 많은 편의성을 제공합니다.