ES6 Fetch API 본문

2021 프론트 엔드 로드맵 따라가기/JS

ES6 Fetch API

알 수 없는 사용자 2021. 6. 9. 04:21

XHR을 이용해 HTTP 요청을 보낼 수 있었던 것처럼 Fetch API를 이용해 HTTP 요청을 보낼 수 있습니다.

 

Fetch API는 Promise 객체를 리턴합니다. 따라서 then 메서드를 이용해 비동기 작업을 진행할 수 있습니다.

 

res에 해당하는 인자는 fetch를 이용해 보낸 HTTP 요청결과에 따른 응답객체가 만들어져 전달됩니다.

 

해당 응답객체의 prototype에 있는 text 메서드를 이용해 해당 응답의 body 내용을 텍스트로 가져올 수 있는데, 해당 메서드의 리턴 결과 또한 Promise 이기 때문에 그에 따른 then 메서드를 이용해야 합니다.

document.querySelector("#button1").addEventListener("click", getText);

function getText() {
  fetch("test.txt")
  .then(function (res) {
    return res.text();
  })
  .then(function (data) {
    document.querySelector("#output").innerHTML = data;
  })
  .catch(function (err) {
    console.log(err);
  });
}

 

Response 객체의 json 메서드를 이용해 해당 응답 body 내용을 object로 가져올 수도 있습니다.

function getJson() {
  fetch("post.json")
  .then(function (res) {
    return res.json();
  })
  .then(function (datas) {
    let output = "";

    datas.forEach(function (data) {
      output += `<li>${data.title}</li>`;
    });

    document.querySelector("#output").innerHTML = output
  });
}

 

fetch API를 이용했을 때는 HTTP 에러가 발생해도 catch 메서드 내부의 함수가 동작하지 않기 때문에 응답받은 Response 객체의 ok 속성의 값에 따라 Error 객체를 생성해 throw 해야합니다.

 

function getText() {
  fetch("test1.txt")
  .then(function (res) {
    if (!res.ok) {
      throw new Error(res.error);
    }

    return res.text();
  })
  .then(function (data) {
    console.log(data);
    document.querySelector("#output").innerHTML = data;
  })
  .catch(function (err) {
    console.log(err);
  });
}

'2021 프론트 엔드 로드맵 따라가기 > JS' 카테고리의 다른 글

ES7 Async & Await  (0) 2021.06.09
ES6 Arrow Function  (0) 2021.06.09
ES6 Promise  (0) 2021.06.09
AJAX POST request  (0) 2021.06.07
AJAX 이용 시 주의할 점  (0) 2021.06.07
Comments