Search

왕종휘_0729

Ajax

Ajax 는 비동기 자바스크립트 통신
브라우저의 XMLHttpRequest 객체를 이용해 페이지의 일부분만 데이터를 로드하는 기법이다.
전체 페이지를 새로고침 하지 않아 오버헤드가 적다.
비동기적 자바스크립트 통신 기술을 통틀어 Ajax라고 한다.
ES2015 표준으로 fetch API가 등장하면서 대부분 Fetch 를 많이 사용한다. (XMLHttpRequest API → jQuery.ajax() → fetch API 순)

Fetch

// 기존적인 fetch fetch('http://example.com/movies.json') .then((response) => response.json()) .then((data) => console.log(data));
JavaScript
복사
fetch() 의 응답은 Response로써 응답의 header,body를 포함하고 있는 개체가 반환된다. 그렇기 때문에 body에 접근하기 위해선 아래와 같은 메서드를 사용해야한다.
arrayBuffer()
blob()
json()
text()
formData()
반환된 자료 변환 메서드는 한번만 사용할 수 있다. response.text()를 통해 응답을 text로 받으면 모두 변환이 된 상태이기 때문에 json()메서드가 작동하지 않는다.

Fetch 요청 옵션

fetch() 의 두번째 인자로 request에 대한 설정을 지정할 수 있다.
fetch(url, { method: 'POST', // *GET, POST, PUT, DELETE 등 mode: 'cors', // no-cors, *cors, same-origin cache: 'no-cache', // *default, no-cache, reload, force-cache, only-if-cached credentials: 'same-origin', // include, *same-origin, omit headers: { 'Content-Type': 'application/json', // 'Content-Type': 'application/x-www-form-urlencoded', }, redirect: 'follow', // manual, *follow, error referrerPolicy: 'no-referrer', // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url body: JSON.stringify(data), // body의 데이터 유형은 반드시 "Content-Type" 헤더와 일치해야 함 });
JavaScript
복사

자바스크립트 async/ await 문법

자바스크립트는 싱글 쓰레드의 단점을 회피하기 위해 비동기 프로그래밍을 사용한다. 그렇기 때문에 동기적인 작업이 필요할 때 callback을 사용하게 되는데 처리과정이 복잡하거나 여러 작업을 순차적으로 실행해야 할때는 콜백 지옥에 빠질 수 있다.
// 콜백 지옥 step1(function (value1) { step2(function (value2) { step3(function (value3) { step4(function (value4) { step5(function (value5) { step6(function (value6) { // Do something with value6 }); }); }); }); }); });
JavaScript
복사
// async/ await 사용 (async () => { let res = await fetch("http://example.com/movies.json"); let text = await res.text(); console.log(text); })()
JavaScript
복사
fetch의 리턴값 response는 Promise 객체이기 때문에 동기작업을 위해 사용한다. (await은 async 함수 내에서만 쓸수 있으니, 익명 함수로 실행)