JS Fetch_API
2020-02-13
Fetch API
-
정의 : Fetch는 네트워크 통신을 포함한 리소스를 가지고 오기 위한 인터페이스를 제공해주는 새로운 API 입니다. XMLHttpRequest와 가능은 같지마느 확장 가능하며 효과적으로 구성되었습니다.
-
특징
- 비동기통신
- Promise 객체
- Http error 상태를 reject하지 못함
- 쿠기를 보내거나 받지 않습니다.(옵션 설정 하면 가능(함수의 두번째 인자))
-
예제 코드
fetch("http://example.com/movies.json") .then(function(response) { return response.json(); }) .then(function(myJson) { console.log(JSON.stringify(myJson)); });
-
Fetch 함수의 두번째 파라미터를 통해 Post 구현
- 기본타입
postData("http://example.com/answer", { answer: 42 }) .then(data => console.log(JSON.stringify(data))) .catch(error => console.error(error)); function postData(url = "", data = {}) { // 디폴트 옵션은 * 로 표시 return fetch(url, { method: "POST", // *GET, POST, PUT, DELETE, etc. 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 referrer: "no-referrer", // no-referrer, *client body: JSON.stringify(data) // body의 data-type은 header의 content-Type과 동일해야 한다. }).then(response => response.json()); // }
- http 객체 Option 중 변경하고 싶은거 반영해서 사용한다.(나머지는 기본값을 지정)
var url = "https://example.com/profile"; var data = { username: "example" }; fetch(url, { method: "POST", // or 'PUT' body: JSON.stringify(data), // data can be `string` or {object}! headers: { "Content-Type": "application/json" } }) .then(res => res.json()) .then(response => console.log("Success:", JSON.stringify(response))) .catch(error => console.error("Error:", error));
- Request, Re 객체를 통해 Fetch()메서드 인수로 보내는것도 가능
var myHeaders = new Headers(); var myInit = { method: "GET", headers: myHeaders, mode: "cors", cache: "default" }; var myRequest = new Request("flowers.jpg", myInit); fetch(myRequest) .then(function(response) { return response.blob(); }) .then(function(myBlob) { var objectURL = URL.createObjectURL(myBlob); myImage.src = objectURL; });