fetch 에 대해 알아보자
데이터 통신에는 Ajax, fetch, Axios 등 다양한 종류가 있다. 그 중 ES6 내장 데이터 통신인 fetch 에 대해 알아보자
fetch 란?
- fetch는 JS의 ES6부터 생긴 내장 라이브러리이다.
- 때문에 별도의 설치 없이 사용할 수 있고, 비동기 통신을 지원한다.
- fetch의 반환값은 promise 객체를 받는다.
- 원래 값을 받으려면 then 을 통해 resolve 객체를 받는다.
1
2
3
fetch(URL , option)
.then((response) => console.log("response:", response)))
.catch((error) => console.log("error:", error));;
위와 같은 코드를 쓰면 option에 따라 URL 에서 데이터를 통신한다.
option의 종류는 다음과 같다.
- 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” 헤더와 일치해야 함
option은 각각의 사용 설정에 맞게 사용하자.!
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.