var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
console.log(xhr.responseText);
} else {
console.error('Error:', xhr.status);
}
}
};
xhr.send();
장단점
장점: 브라우저에서 기본적으로 제공되므로 별도의 라이브러리나 패키지를 설치할 필요가 없습니다.
단점: 비교적 사용법이 복잡하고 코드가 길어질 수 있습니다.
콜백 지옥(callback hell)에 빠질 수 있으며, 코드의 가독성과 유지보수성이 떨어질 수 있습니다
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
장단점
장점: 간단하고 직관적인 API를 제공합니다.
Promise를 기반으로 하여 비동기 코드를 보다 깔끔하게 작성할 수 있습니다.
단점: 오래된 브라우저에서는 지원되지 않을 수 있으므로 폴리필(polyfill)이 필요할 수 있습니다.
기능이 제한적일 수 있으며, 좀 더 복잡한 요청을 다루기에는 다소 부족할 수 있습니다.
import axios from 'axios';
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));
장단점
장점: 간단한 API를 제공하면서도 다양한 설정과 기능을 제공합니다.
HTTP 요청과 응답을 다루는데 편리한 메서드와 인터셉터(interceptor)를 제공합니다.
단점: 추가적인 라이브러리로 설치해야 하므로 번들 크기가 커질 수 있습니다.
기본적으로 브라우저와 Node.js 환경에서만 사용할 수 있으므로, 리액트 네이티브와 같은 다른 환경에서는 사용할 수 없습니다.