fetch


fetch(url).then((res) => console.log(res));

  • fetch 함수는 Promise 방식을 지원하고 HTTP request 기능을 제공하는 함수입니다. fetch 함수는 HTTP 응답을 나타내는 Response 객체를 래핑한 Promise 객체를 반환합니다. 그리고 res 객체에는 HTTP 응답을 나타내는 다양한 프로퍼티를 제공합니다.

  • featch 에러는 서버로부터 온 응답이 404 또는 500이여도 rejected 상태가 되지 않고 fulfilled 상태가 됩니다. rejected 상태가 되는 경우는 네트워크 장애나 CORS 에러에 의해 요청이 완료되지 못한 경우에는 Promise를 rejected 합니다.




fetch 사용 예시


fetch(url).then((res) => {}); // method를 설정하지 않으면 GET으로 정의합니다.

fetch(url, {
  method: "POST", // or PUT, PATCH
  headers: { "Content-Type": "application/json" },
  body: JSON.stringify(payload),
}).then((res) => {});

fetch(url, { method: "DELETE" }).then((res) => {});



// async/await 을 사용한 버전

(async () => {
  const res = await fetch(url);
})();

(async () => {
  fetch(url, {
    method: "POST", // or PUT, PATCH
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(payload),
  });
})();

(async () => {
  fetch(url, { method: "DELETE" }).then((res) => {});
})();




+ Recent posts