JS fetch

정현승·2024년 11월 6일

fetch 문법 사용법

fetch 메서드는 기본적으로 첫 번째 인자로 요청할 URL을 받으며, 기본적으로 HTTP 메소드 중 GET 방식으로 동작합니다.

fetch("https://jsonplaceholder.typicode.com/posts", option)
   .then(res => res.json())
   .then(data => console.log(data));

fetch를 통해 호출할 경우, 해당 URL로 요청을 보내면 응답 객체(Promise 객체 Response)를 받게 됩니다.
첫 번째 .then에서 이 응답을 받고, res.json() 메서드를 사용하여 JSON 형식으로 파싱한 값을 리턴합니다.
그다음 .then에서 파싱된 데이터를 받아 원하는 처리를 할 수 있습니다.

fetch의 response 속성

  • response.status – HTTP 상태 코드 (예: 200)
  • response.ok – HTTP 상태 코드가 200과 299 사이일 경우 true
  • response.body – 내용

응답 자료 형태 반환 메서드

  • response.text() – 응답을 텍스트로 반환합니다.
  • response.json() – 응답을 JSON 형태로 파싱합니다.
  • response.formData() – 응답을 FormData 객체로 반환합니다.
  • response.blob() – 응답을 Blob(타입이 있는 바이너리 데이터) 형태로 반환합니다.
  • response.arrayBuffer() – 응답을 ArrayBuffer 형태로 반환합니다.

이러한 응답 자료 형태 반환 메서드는 한 번만 사용할 수 있습니다.
예를 들어, response.text()를 사용하여 응답을 한 번 가져오면 본문 콘텐츠는 이미 처리된 상태이므로,
이후에 response.json() 등을 호출해도 동작하지 않습니다.

Fetch - CRUD 요청하기

HTTP 요청에는 GET, POST, PUT, DELETE 등 여러 가지가 있습니다.

fetch - GET Method

GET : 존재하는 자원을 요청하는 데 사용됩니다.

  • 단순히 원격 API에서 데이터를 가져올 때 사용합니다.
  • fetch 함수는 기본적으로 GET 방식으로 작동하므로 옵션 인자가 필요 없습니다.
fetch("https://jsonplaceholder.typicode.com/posts/1") // posts의 id 1인 엘리먼트를 가져옴 
  .then((response) => response.json())
  .then((data) => console.log(data))

fetch - POST Method

POST : 새로운 자원을 생성할 때 사용됩니다.

  • 데이터 양이 많거나 비밀번호 등 개인정보를 보낼 때 사용됩니다.
  • 새로운 포스트를 생성하려면 method 옵션을 POST로 지정하고, headers 옵션으로 JSON 포맷을 사용한다고 명시해주어야 합니다.
  • body 옵션에는 JSON 포맷의 요청 데이터를 포함해야 합니다.
fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "POST", // POST
  headers: { // 헤더 조작
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ // 자바스크립트 객체를 json화 한다.
    title: "Test",
    body: "I am testing!",
    userId: 1,
  }),
})
  .then((response) => response.json())
  .then((data) => console.log(data))

fetch - PUT Method (전체수정)

PUT : 존재하는 자원 전체를 변경할 때 사용됩니다.

  • 전체를 body의 데이터로 교체합니다.
fetch("https://jsonplaceholder.typicode.com/posts", {
  method: "PUT",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    title: "Test" // 아예 title 엘리먼트로 전체 데이터를 바꿈. 마치 innerHTML같이.
  }),
})
  .then((response) => response.json())
  .then((data) => console.log(data))

fetch - PATCH Method (부분수정)

PATCH : 존재하는 자원의 일부를 변경할 때 사용됩니다.

  • body 데이터에 해당하는 일부만 교체합니다.
fetch("https://jsonplaceholder.typicode.com/posts/1", { // posts의 id 1인 엘리먼트를 수정
  method: "PATCH",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({
    title: "Test" // title만 바꿈. 나머지 요소는 건들지 않음.
  }),
})
  .then((response) => response.json())
  .then((data) => console.log(data))

fetch - DELETE Method

DELETE : 존재하는 자원을 삭제할 때 사용됩니다.

  • 데이터를 전송하지 않으므로 headers, body 옵션이 필요 없습니다.
fetch("https://jsonplaceholder.typicode.com/posts/1", {
  method: "DELETE",
})
  .then((response) => response.json())
  .then((data) => console.log(data))

Fetch - async / await

await / async 문법으로 보다 가독성을 높일 수 있습니다.

fetch("https://jsonplaceholder.typicode.com/posts", option)
.then(res => res.json())
.then(data => console.log(data));
const getPost = async() => {
  let res = await fetch("https://jsonplaceholder.typicode.com/posts", option);
  let data = await res.json();
  console.log(data);
}

fetch 모듈화

fetch() 함수는 기본적으로 간단하게 사용할 수 있지만, 자주 반복하여 사용하다 보면 코드가 중복될 수 있습니다.
예를 들어, 응답 데이터를 가져오기 위해 매번 response.json()을 호출하거나, 데이터를 전송할 때 HTTP 요청 헤더에 "Content-Type": "application/json"를 일일이 설정해야 합니다.
이러한 반복 작업을 줄이기 위해 헬퍼 함수를 만들어 모듈화해 두면, 나중에 훨씬 편리하게 사용할 수 있습니다.

const fetchData = async (url, options = {}) => {
  try {
    const response = await fetch(url, {
      method: "GET",
      ...options, // 추가 헤더 또는 옵션을 받아 병합
    });
    
    // 요청이 성공적으로 이루어졌는지 확인
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }

    // JSON 형식으로 응답 처리
    const data = await response.json();
    return data;
    
  } catch (error) {
    console.error("Fetch Error:", error);
    return null;
  }
};
fetchData("https://jsonplaceholder.typicode.com/posts")
  .then(data => {
    if (data) {
      console.log("Fetched Data:", data);
    } else {
      console.log("No data returned.");
    }
  });
  • fetchData 함수는 URL과 추가 옵션(헤더 등)을 인자로 받아 GET 요청을 수행합니다.
  • options 매개변수는 기본적으로 빈 객체로 설정되며, 필요시 커스터마이징 할 수 있습니다.
  • 에러 처리는 .ok 속성을 통해 상태 코드가 200대인지 확인 후, 에러 메시지를 출력합니다.
  • 결과 반환: JSON 데이터를 파싱하여 반환하며, 실패할 경우 null을 반환합니다.

0개의 댓글