JavaScript에서의 Fetch/XMLHttpRequest

JavaScript에서의 Fetch/XMLHttpRequest

이 글은 JavaScript에서 Fetch/XMLHttpRequest를 설명합니다.

YouTube Video

javascript-html-fetch-xhr.html
  1<!DOCTYPE html>
  2<html lang="en">
  3<head>
  4  <meta charset="UTF-8">
  5  <title>JavaScript &amp; HTML</title>
  6  <style>
  7    * {
  8        box-sizing: border-box;
  9    }
 10
 11    body {
 12        margin: 0;
 13        padding: 1em;
 14        padding-bottom: 10em;
 15        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
 16        background-color: #f7f9fc;
 17        color: #333;
 18        line-height: 1.6;
 19    }
 20
 21    .container {
 22        max-width: 800px;
 23        margin: 0 auto;
 24        padding: 1em;
 25        background-color: #ffffff;
 26        border: 1px solid #ccc;
 27        border-radius: 10px;
 28        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
 29    }
 30
 31    .container-flex {
 32        display: flex;
 33        flex-wrap: wrap;
 34        gap: 2em;
 35        max-width: 1000px;
 36        margin: 0 auto;
 37        padding: 1em;
 38        background-color: #ffffff;
 39        border: 1px solid #ccc;
 40        border-radius: 10px;
 41        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
 42    }
 43
 44    .left-column, .right-column {
 45        flex: 1 1 200px;
 46        min-width: 200px;
 47    }
 48
 49    h1, h2 {
 50        font-size: 1.2rem;
 51        color: #007bff;
 52        margin-top: 0.5em;
 53        margin-bottom: 0.5em;
 54        border-left: 5px solid #007bff;
 55        padding-left: 0.6em;
 56        background-color: #e9f2ff;
 57    }
 58
 59    button {
 60        display: block;
 61        margin: 1em auto;
 62        padding: 0.75em 1.5em;
 63        font-size: 1rem;
 64        background-color: #007bff;
 65        color: white;
 66        border: none;
 67        border-radius: 6px;
 68        cursor: pointer;
 69        transition: background-color 0.3s ease;
 70    }
 71
 72    button:hover {
 73        background-color: #0056b3;
 74    }
 75
 76    #output {
 77        margin-top: 1em;
 78        background-color: #1e1e1e;
 79        color: #0f0;
 80        padding: 1em;
 81        border-radius: 8px;
 82        min-height: 200px;
 83        font-family: Consolas, monospace;
 84        font-size: 0.95rem;
 85        overflow-y: auto;
 86        white-space: pre-wrap;
 87    }
 88
 89    .highlight {
 90        outline: 3px solid #ffc107; /* yellow border */
 91        background-color: #fff8e1;  /* soft yellow background */
 92        transition: background-color 0.3s ease, outline 0.3s ease;
 93    }
 94
 95    .active {
 96        background-color: #28a745; /* green background */
 97        color: #fff;
 98        box-shadow: 0 0 10px rgba(40, 167, 69, 0.5);
 99        transition: background-color 0.3s ease, box-shadow 0.3s ease;
100    }
101  </style>
102</head>
103<body>
104    <div class="container">
105        <h1>JavaScript Console</h1>
106        <button id="executeBtn">Execute</button>
107        <div id="output"></div>
108    </div>
109
110    <script>
111        // Override console.log to display messages in the #output element
112        (function () {
113            // Override console.log
114            const originalLog = console.log;
115            console.log = function (...args) {
116                originalLog.apply(console, args);
117                const message = document.createElement('div');
118                message.textContent = args.map(String).join(' ');
119                output.appendChild(message);
120            };
121
122            // Override console.error
123            const originalError = console.error;
124            console.error = function (...args) {
125                originalError.apply(console, args);
126                const message = document.createElement('div');
127                message.textContent = args.map(String).join(' ');
128                message.style.color = 'red'; // Color error messages red
129                output.appendChild(message);
130            };
131        })();
132
133        document.getElementById('executeBtn').addEventListener('click', () => {
134            // Prevent multiple loads
135            if (document.getElementById('externalScript')) return;
136
137            const script = document.createElement('script');
138            script.src = 'javascript-html-fetch-xhr.js';
139            script.id = 'externalScript';
140            //script.onload = () => console.log('javascript-html-fetch-xhr.js loaded and executed.');
141            //script.onerror = () => console.log('Failed to load javascript-html-fetch-xhr.js.');
142            document.body.appendChild(script);
143        });
144    </script>
145</body>
146</html>

JavaScript에서의 Fetch/XMLHttpRequest

JavaScript에서 FetchXMLHttpRequest(XHR)는 모두 HTTP 요청을 보내고 서버에서 데이터를 가져오는 데 사용됩니다.

Fetch API

Fetch API는 XHR을 대체하기 위해 설계된 HTTP 요청을 처리하는 현대적인 방법입니다. Promise 기반의 비동기 API로, 더 간단하고 유연하게 요청을 처리할 수 있게 해줍니다.

사용 방법

 1fetch('http://127.0.0.1:3000/example.json')
 2    .then((response) => {
 3        if (!response.ok) {
 4            throw new Error('HTTP error: ' + response.status);
 5        }
 6        return response.json();  // Parse the response as JSON
 7    })
 8    .then((data) => {
 9        console.log(data);  // Use the fetched data
10        console.log(JSON.stringify(data));
11    })
12    .catch((error) => {
13        console.error('An error occurred:', error);  // Error handling
14    });
  • 이 코드는 Fetch API를 사용하여 지정한 URL에 GET 요청을 보내고, 응답을 JSON으로 처리하여 결과를 표시하거나 오류를 출력합니다.

기능

Fetch API는 다음과 같은 특징을 가지고 있습니다:.

  • 프로미스(Promise) 기반 비동기 작업을 프로미스(Promise)로 관리할 수 있어 코드가 더 깔끔하고 읽기 쉬워집니다.
  • 쉬운 오류 처리 catch 블록을 사용하여 오류를 쉽게 처리할 수 있습니다.
  • response.json()과 같은 메서드를 통한 파싱 응답 데이터를 JSON이나 텍스트 형식으로 쉽게 처리할 수 있습니다.
  • CORS 지원 Fetch는 교차 출처 리소스 공유(CORS) 규칙을 기반으로 동작합니다.
  • 유연한 요청 설정 GET/POST뿐만 아니라 PUT, DELETE와 같은 HTTP 메서드도 쉽게 설정할 수 있습니다.

예시: POST 요청

 1fetch('http://127.0.0.1:3000/example.json', {
 2        method: 'POST',
 3        headers: {
 4            'Content-Type': 'application/json'
 5        },
 6        body: JSON.stringify({ name: 'Alice', age: 25 })  // Send the request body as JSON
 7    })
 8    .then(response => response.json())
 9    .then(data => console.log(JSON.stringify(data)))
10    .catch(error => console.error('Error:', error));
  • 이 코드는 JSON 데이터를 포함한 POST 요청을 보내고, 서버로부터 받은 응답을 JSON으로 표시합니다.

단점

Fetch API는 다음과 같은 단점이 있습니다:.

  • 브라우저 호환성 구형 브라우저(특히 IE11)는 Fetch API를 지원하지 않습니다.
  • 세밀한 제어가 어렵다 XHR에 비해 진행 이벤트 처리와 같은 저수준 제어에는 적합하지 않습니다.

XMLHttpRequest(XHR)

XMLHttpRequest는 HTTP 요청을 처리하기 위해 오랫동안 사용되어 왔으며 AJAX(비동기 JavaScript 및 XML)의 기본으로 널리 사용되었습니다. 전체 페이지를 새로고침하지 않고도 비동기 통신을 통해 서버에서 데이터를 가져올 수 있습니다.

사용 방법

 1const xhr = new XMLHttpRequest();
 2xhr.open('GET', 'http://127.0.0.1:3000/example.json', true);
 3xhr.onreadystatechange = function() {
 4    if (xhr.readyState === 4 && xhr.status === 200) {
 5        const data = JSON.parse(xhr.responseText);  // Parse the response as JSON
 6        console.log(data);  // Use the data
 7        console.log(JSON.stringify(data));
 8    }
 9};
10xhr.send();  // Send the request
  • 이 코드는 XMLHttpRequest를 사용하여 GET 요청을 보내고, 받은 JSON 응답을 파싱하여 표시합니다.

기능

XMLHttpRequest는 다음과 같은 특징이 있습니다:.

  • 콜백(callback) 기반 onreadystatechange와 같은 콜백 함수를 사용하여 요청의 완료나 진행 상황을 감시합니다.
  • 상태 코드 및 readyState 감시 xhr.readyStatexhr.status를 통해 요청 상태를 확인할 수 있습니다.
  • 넓은 호환성 구형 브라우저에서도 동작합니다.
  • 요청 진행 상황 감시 xhr.upload.onprogress와 같은 이벤트로 진행 상황을 감시할 수 있습니다.

예시: POST 요청

 1const xhr = new XMLHttpRequest();
 2xhr.open('POST', 'http://127.0.0.1:3000/example.json', true);
 3xhr.setRequestHeader('Content-Type', 'application/json');
 4xhr.onreadystatechange = function() {
 5    if (xhr.readyState === 4 && xhr.status === 200) {
 6        const data = JSON.parse(xhr.responseText);
 7        console.log(data);
 8        console.log(JSON.stringify(data));
 9    }
10};
11xhr.send(JSON.stringify({ name: 'Alice', age: 25 }));  // Send the data
  • 이 코드는 XMLHttpRequest를 이용하여 JSON 데이터를 담은 POST 요청을 보내고, 응답을 받아 표시합니다.

단점

XMLHttpRequest는 다음과 같은 단점이 있습니다:.

  • 복잡한 코드 콜백 함수로 비동기 처리를 관리하면 코드가 복잡해지는 경향이 있습니다.
  • 프로미스(Promise) 기본 지원 없음 기본적으로 프로미스를 지원하지 않기 때문에 비동기 처리가 다소 장황해집니다.

Fetch APIXMLHttpRequest 비교

기능 Fetch API XMLHttpRequest (XHR)
비동기 처리 Promise로 간단함 콜백 함수가 필요함
에러 처리 .catch()로 관리 가능 readyState 상태를 확인
진행 이벤트 지원하지 않음 onprogress로 처리
크로스 오리진 지원 CORS를 자동으로 지원함 CORS 지원
브라우저 지원 IE11 및 이전 버전을 지원하지 않음 오래된 브라우저와 호환 가능
제어 세분성 간단하고 직관적임 세부적인 제어 가능

요약

  • Fetch API는 Promises를 기반으로 간단하고 유연한 HTTP 요청을 제공하며, 최신 브라우저에서 권장됩니다.

위의 기사를 보면서 Visual Studio Code를 사용해 우리 유튜브 채널에서 함께 따라할 수 있습니다. 유튜브 채널도 확인해 주세요.

YouTube Video