느바 2025. 1. 4. 13:28
반응형

Fetch API

Fetch API는 JavaScript에서 네트워크 요청을 보내고 데이터를 가져오기 위해 사용하는 표준화된 인터페이스입니다. 주로 HTTP 요청을 보내 서버와 통신하거나 데이터를 가져오는 작업에 사용됩니다. 이전에 사용되던 XMLHttpRequest에 비해 더 직관적이고 간결한 문법을 제공합니다.


특징

  1. Promise 기반:
    • fetch는 Promise를 반환하므로, 비동기 작업을 간편하게 처리할 수 있습니다.
    • async/await 문법과 함께 사용하기에 적합합니다.
  2. 모듈화된 설계:
    • 요청과 응답을 Request와 Response 객체로 캡슐화하여 작업을 명확히 분리합니다.
  3. 확장 가능성:
    • 다양한 옵션을 통해 HTTP 메서드, 헤더, 본문 등을 설정할 수 있습니다.
  4. 기본 JSON 처리:
    • 응답 데이터를 JSON으로 쉽게 변환할 수 있는 .json() 메서드를 제공합니다.

기본 사용법

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json(); // JSON 데이터를 파싱
  })
  .then(data => {
    console.log(data); // 가져온 데이터 처리
  })
  .catch(error => {
    console.error('There has been a problem with your fetch operation:', error);
  });
 

옵션 설정

fetch 메서드는 두 번째 매개변수로 요청 옵션을 받습니다. 예:

fetch('https://api.example.com/data', {
  method: 'POST', // HTTP 메서드
  headers: {
    'Content-Type': 'application/json' // 요청 헤더 설정
  },
  body: JSON.stringify({ key: 'value' }) // 요청 본문
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error(error));
 

중요한 점

  1. CORS:
    • fetch를 사용할 때 CORS(Cross-Origin Resource Sharing) 정책이 적용됩니다.
    • 서버에서 적절한 헤더를 설정하지 않으면 요청이 차단될 수 있습니다.
  2. 오류 처리:
    • HTTP 오류 상태 코드(예: 404, 500)는 Promise를 거부하지 않습니다. 따라서 response.ok로 상태를 확인해야 합니다.
  3. 비동기 처리:
    • Promise 또는 async/await 문법을 사용하여 코드의 가독성을 높이고 비동기 흐름을 관리할 수 있습니다.

Example: async/await 사용

async function fetchData() {
  try {
    const response = await fetch('https://api.example.com/data');
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Fetch error:', error);
  }
}

fetchData();
<!DOCTYPE html>
<head>
    <title>fetch 예시</title>
</head>
<body>
    <div id="content"></div>
    <script>
        const API_URL = 'https://animal-api-two.vercel.app/';
        const $content = document.querySelector('#content');
        let template = [];

        const request = async () => {            
            let res = await fetch(API_URL);

            try {
                if (res) {
                    let data = await res.json();

                    data.photos.forEach((elm) => {
                        template += `<img src="${elm.url}"></img>`;
                    });
                    $content.innerHTML = template;
                }
            } catch (error) {
                console.log(error);
            }
        };

        request();
    </script>
</body>

</html>

대체 API와의 비교

  1. XMLHttpRequest:
    • 복잡하고 콜백 지옥(callback hell) 문제를 유발할 수 있음.
    • fetch는 Promise 기반으로 설계되어 더 깔끔한 코드를 작성할 수 있음.
  2. Axios:
    • 더 많은 기능을 제공하는 서드파티 라이브러리.
    • fetch보다 간결한 문법과 향상된 오류 처리 제공.

Fetch는 브라우저에서 기본적으로 지원되기 때문에 외부 라이브러리를 설치할 필요가 없지만, Axios와 같은 라이브러리가 더 풍부한 기능을 제공할 때도 있습니다.