js를 사용한 비동기 통신, 클라이언트와 서버간에 데이터를 주고 받는 기술
ajax 요청을 보내기 위해서는 XMLHttpRequest
객체를 사용한다.
const xhr = new XMLHttpRequest();
xhr.open('GET', 'https://api.example.com/data', true);
xhr.onload = function(){
if(xhr.status >= 200 && xhr.statuas <300){
console.log(xhr.responseText);
}else{
console.error('Request failed');
}
};
xhr.send();
jquery
와 함께 사용하면 조금 더 직관적이고 쉬워진다.const serverAddress = 'https://jsonplaceholder.typicode.com/posts';
$.ajax({
url : serverAddress,
type : 'GET',
success : function onData(data){console.log(data);},
error : function onError(error){console.error(error);}
})
기존의 웹에서 어떤 리소스를 비동기로 요청하기 위해서는 XHR(XML HTTP REQUEST) 객체를 사용해야하는데, 이는 사실 좋은 API가 아니다.
요청의 상태
나 변경
을 구독하려면 Event를 등록해서 변경사항을 받아야하고,
요청의 성공
, 실패
여부나 상태에 따라 처리하는 로직이 들어가기 좋지 않다.
때문에 이를 보완하기 위해서 http
요청을 쉽게할 수 있도록 도와주는 자바스크립트 라이브러리가 나왔고, axios
는 그중 하나.
promise
기반으로 동작하며, 비동기 처리를 간단하게 할 수 있다.
Fetch api
는 최신 브라우저에서 지원하는 내장된 api이다. 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(`fetch Error : ${error}`);