fetch 사용법

2022. 7. 18. 00:39
반응형
fetch('http://example.com/movies.json')
  .then((response) => response.json())
  .then((data) => console.log(data));

Fetch는 이전까지 사용하던 Ajax를 대체하는 API다.

익스플로러11이 이제 서비스 종료가 되었으니 Fetch를 쓰는 것이 더 나아 보임. 코드도 훨씬 간단하다.

 

Ajax는 XMLHttpRequest (XHR) 객체를 사용하여 서버와 통신하는 기술이었는데

Fetch는 promise 객체를 반환한다. 응답할 때는 response 객체를 받고, 이를 json()로 파싱할 수 있다.

Http 오류 상태도 수신하지만 200~299 범위가 넘어가는 경우에는 ok 속성을 false로 바꾼다.

// POST 메서드 구현 예제
async function postData(url = '', data = {}) {
  // 옵션 기본 값은 *로 강조
  const response = await 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" 헤더와 일치해야 함
  });
  return response.json(); // JSON 응답을 네이티브 JavaScript 객체로 파싱
}

postData('https://example.com/answer', { answer: 42 }).then((data) => {
  console.log(data); // JSON 데이터가 `data.json()` 호출에 의해 파싱됨
});

 

 

※ Fetch에는 timeout이 없고, 요청취소가 존재하지 않았었는데, 이 때문에 axios라는 라이브러리를 사람들이 많이 사용한다. 그러나 현재 fetch에는 abort controller를 이요해서 요청취소를 구현할 수 있음. 그럼에도 axios의 가독성과 다양한 기능 때문에 사용하는 사람들이 많다.

 

https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fetch

 

Fetch 사용하기 - Web API | MDN

Fetch API는 HTTP 파이프라인을 구성하는 요청과 응답 등의 요소를 JavaScript에서 접근하고 조작할 수 있는 인터페이스를 제공합니다. Fetch API가 제공하는 전역 fetch() (en-US) 메서드로 네트워크의 리소

developer.mozilla.org

 

 

반응형

BELATED ARTICLES

more