AJAX
AJAX
기존에는 클라이언트가 요청을 하면 기존 연결(현재 페이지)이 끊기고 서버가 응답처리를 합니다. 따라서 서버에 요청할때마다 응답을 새로 받기때문에 현재 페이지가 새로고침됩니다. 이는 일부 데이터만 원할지라도 다른 모든 데이터도 응답으로 받기 때문에 자원소모가 큽니다. AJAX란 이러한 문제를 해결하고자 XMLHttpRequest 객체를 통해 기존 연결(현재 페이지)를 유지한채로 서버와 통신하는 기술을 의미합니다.
📔 참고자료 : https://developer.mozilla.org/ko/docs/Web/Guide/AJAX/Getting_Started
📔 참고자료 : https://velog.io/@surim014/AJAX란-무엇인가
AJAX 만들기
AJAX 통신을 위해 XMLHttpRequest가 필요합니다.
- XMLHttpRequest
서버와 상호작용할 수 있는 객체입니다. XMLHttpRequest 객체를 통해 전체 페이지를 새로고침하지 않아도 URL로부터 서버의 데이터를 가져올 수 있습니다. 따라서 사용자의 페이지 사용을 방해하지 않으면서 현재 페이지의 일부를 업데이트 할 수 있습니다.
📔 참고자료 : https://developer.mozilla.org/ko/docs/Web/API/XMLHttpRequest
const xhr = new XLMHttpRequest();
- onreadystatechange
readystate가 바뀌면 콜백을 실행시킵니다. 따라서, readystate에 따른 작업을 처리할 수 있습니다.
😺 콜백은 단지 readystate가 바뀌면 실행되기 때문에, 인자가 없습니다.
📔 참고자료 : https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/onreadystatechange
const xhr = new XLMHttpRequest();
xhr.onreadystatechange = () => {
console.log('ready state change')
}
- readystate
readystate는 XMLHttpRequest 상태를 보여주며, 다음은 readystate의 상태들을 보여줍니다.
- 🔎 readystate 상태
const xhr = new XLMHttpRequest();
const xhrReadyState = xhr.readystate;
$ajaxButton.addEventListener("click", () => {
const xhr = new XMLHttpRequest();
xhr.onreadystatechange = () => {
console.log("AJAX Response Success");
console.log(xhr.responseText);
console.log(xhr.responseXML);
console.log(xhr.status, xhr.statusText);
};
xhr.open("GET", "http://localhost:3000/login");
xhr.send();
});
Fetch
XMLHttpRequest 객체를 통해 AJAX 통신을 하면 코드가 복잡해집니다. 따라서 이를 해결하고자 ES6부터 Fetch API가 만들어졌습니다. Fetch API에 요청 url, 요청 데이터, 요청환경 등을 설정하여 서버에 요청을 보내면, 서버는 reponse(promise)를 반환합니다. 받은 response를 arrayBuffer / blob / json / test / formData를 통해 body를 parsing해야하며 이들은 promise를 반환합니다. 아래는 이에 대한 예제코드입니다.
📔 참고자료 : https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fetch
📔 참고자료 : https://junhobaik.github.io/ajax-xhr-fetch/
📔 참고자료(response 객체) : https://developer.mozilla.org/en-US/docs/Web/API/Response
- 🔎 Fetch 예제코드
- then 체이닝
fetch('https://study.com/home', { method: 'POST', body: JSON.stringify({a: 'nodejs'}), headers:{ 'Content-Type': 'application/json' } }).then(response => response.json()) .then(data => ...) .catch(err => ...);
- async / await
const response = await fetch('https://study.com/home', { method: 'POST', body: JSON.stringify({a: 'nodejs'}), headers:{ 'Content-Type': 'application/json' } }). const data = await response.json();
AXIOS
AJAX 통신을 위한 라이브러리입니다. npm install axios
로 설치하며 require('axios')
로 가져옵니다. AXIOS는 Fetch와 유사하지만, 응답시간 초과, 요청 취소 등을 다룰 수 있다는 점에서 Fetch 보다 AJAX를 자유롭게 다룰 수 있습니다.
📔 참고자료 : https://www.npmjs.com/package/axios
- 🔎 AXIOS 예제코드
- then 체이닝
axios( url: 'https://study.com/home', method: 'POST', headers:{ 'Content-Type': 'application/json' }, data: {a: 'nodejs'}, }).then(response => ...) .catch(err => ...);
- async / await
const response = await axios( url: 'https://study.com/home', method: 'POST', headers:{ 'Content-Type': 'application/json' }, data: {a: 'nodejs'}, })