728x90
반응형
AJAX, Axios, Fetch: 웹 개발에서 비동기 요청 처리의 모든 것
비동기식 자바스크립트와 XML(Asynchronous JavaScript and XML),
즉 AJAX는 웹 애플리케이션의 성능과 사용자 경험을 개선하는 데에 아주 필수적인 기술이다.
기본적으로 AJAX를 사용하면 페이지를 다시 로드하지 않고도 서버와 통신할 수 있다.
AJAX라는 전통적인 사용법 외에도, Axios와 Fetch API는 모던 웹 개발에서 비동기 요청을 처리하는 데 널리 사용되고 있다.
1. AJAX
첫째로 가장 전통적인 방식은 AJAX는 비동기적으로 서버와 통신하여 데이터를 주고받는 기술이다.
AJAX는 여러 웹 기술을 조합하여 비동기 요청을 처리하는 역할을 한다.
비동기성(페이지 리로드 없이 서버와 통신할 수 있다!), 사용자 경험 개선(동적인 웹 페이지), 효율성(필요한 데이터만 전송하여 대역폭을 절약)때문에 사용이 시작됐다.
- AJAX가 포함하는 기술 목록
- HTML/XHTML와 CSS: 웹 페이지의 구조와 스타일 정의
- DOM: JavaScript를 사용해 동적으로 웹 페이지를 조작
- XML 또는 JSON: 서버와 주고받는 데이터 형식
- XMLHttpRequest 객체: 브라우저에서 서버로 비동기 HTTP 요청 전송
- JavaScript: 위의 모든 기술을 조합!
기본적인 AJAX 사용법
AJAX 사용법은 XMLHttpRequest
객체를 사용법 익히기와 거의 같다.
<!DOCTYPE html>
<html>
<head>
<title>AJAX Example</title>
</head>
<body>
<button id="loadData">Load Data</button>
<div id="result"></div>
<script>
document.getElementById('loadData').addEventListener('click', function() {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'data.json', true);
xhr.onreadystatechange = function() {
if (xhr.readyState === 4 && xhr.status === 200) {
document.getElementById('result').innerHTML = xhr.responseText;
}
};
xhr.send();
});
</script>
</body>
</html>
2. Fetch API
Fetch API는 비동기 네트워크 요청을 보다 간단하게 할 수 있게 해주는 모던(최신식) JavaScript API다.
Fetch를 쓴다면 어떤 이유에서 쓸까?
- Promise 기반이라 콜백 헬(callback hell)을 피하고, 더 읽기 쉬운 코드를 작성할 수 있다.
fetch('https://api.example.com/data') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
- 추가적인 라이브러리를 설치할 필요가 없는 내장 AP라 프로젝트의 종속성을 최소화해야 할 때 상당히 유리하다.
Request
와Response
객체를 사용해HTTP
요청과 응답을 보다 명확하게 다룰 수 있다.const requestOptions = { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ key: 'value' }) }; fetch('https://api.example.com/data', requestOptions) .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error('Error:', error));
- 큰 파일이나 데이터 스트림을 다룰 때 유용한다. ReadableStream 인터페이스가 있어 통해 응답을 스트리밍 방식으로 처리할 수 있다.
fetch('https://api.example.com/largefile') .then(response => { const reader = response.body.getReader(); const stream = new ReadableStream({ start(controller) { function push() { reader.read().then(({ done, value }) => { if (done) { controller.close(); return; } controller.enqueue(value); push(); }); } push(); } }); return new Response(stream); }) .then(response => response.blob()) .then(blob => { const url = URL.createObjectURL(blob); const a = document.createElement('a'); a.href = url; a.download = 'largefile.dat'; document.body.appendChild(a); a.click(); a.remove(); }) .catch(error => console.error('Error:', error));
Fetch API 사용법
<!DOCTYPE html>
<html>
<head>
<title>Fetch API Example</title>
</head>
<body>
<button id="loadData">Load Data</button>
<div id="result"></div>
<script>
document.getElementById('loadData').addEventListener('click', function() {
fetch('data.json')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok ' + response.statusText);
}
return response.json();
})
.then(data => {
document.getElementById('result').innerHTML = JSON.stringify(data);
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
});
</script>
</body>
</html>
3. Axios
Axios는 비동기 HTTP 요청을 처리하기 위해 설계된 JavaScript 라이브러리로, Node.js와 브라우저 환경 모두에서 사용할 수 있다.
Promise 기반, 간편한 API, 브라우저 호환성, 자동 JSON 변환, 취소 토큰, 인터셉터가 가능하다.
Axios 설치
npm install axios
Axios 사용법
<!DOCTYPE html>
<html>
<head>
<title>Axios Example</title>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>
<body>
<button id="loadData">Load Data</button>
<div id="result"></div>
<script>
document.getElementById('loadData').addEventListener('click', function() {
axios.get('data.json')
.then(response => {
document.getElementById('result').innerHTML = JSON.stringify(response.data);
})
.catch(error => {
console.error('There was an error!', error);
});
});
</script>
</body>
</html>
4. AJAX vs. Fetch vs. Axios
각 방법의 장단점을 비교
4.1. AJAX(XMLHttpRequest)
- 장점:
- 구형 브라우저에서도 지원
- 다중 이벤트 리스너를 사용할 수 있습니다.
- 단점:
- 콜백 헬 문제로 코드가 복잡해질 수 있습니다.
- JSON 데이터 처리가 번거롭습니다.
4.2. Fetch API
- 장점:
- Promise 기반으로 더 간단하고 직관적인 코드 작성이 가능합니다.
- 최신 표준으로서 모던한 기능을 제공합니다.
- 단점:
- 구형 브라우저에서는 지원되지 않을 수 있습니다.
- HTTP 에러가 throw되지 않아 명시적인 오류 처리가 필요합니다.
4.3. Axios
- 장점:
- Promise 기반으로 사용이 간편합니다.
- 요청 및 응답 인터셉터, 요청 취소 등 다양한 기능을 제공합니다.
- 자동 JSON 변환 기능이 있습니다.
- 브라우저와 Node.js 환경 모두에서 사용 가능합니다.
- 단점:
- 추가적인 라이브러리 설치가 필요합니다.
- 라이브러리 크기가 Fetch API보다 크기 때문에 용량이 신경 쓰일 수 있습니다.
728x90
반응형
'Front-end' 카테고리의 다른 글
개발자를 위한 SEO: 프론트엔드 개발자가 알아야 할 모든 것 🔍 (0) | 2024.11.22 |
---|---|
[Web Pack] 웹팩, 현대 웹 개발의 필수 도구! 👍 (3) | 2024.10.28 |
React와 Vue의 라이프사이클 톺어보기 (1) | 2024.10.07 |
React와 Vue에서 undefined와 맞짱뜨는 법 (0) | 2024.09.23 |
Form 태그 톺아보기! (0) | 2024.07.29 |