JavaScript Fetch API


Fetch API는 자바스크립트에서 네트워크 요청을 수행하고 응답을 처리하기 위해 사용하는 현대적인 API입니다. XMLHttpRequest의 대안으로, 비동기 HTTP 요청을 더 간결하고 직관적으로 처리할 수 있도록 설계되었습니다. fetch는 프로미스(Promise)를 반환하여 비동기 작업을 쉽게 다룰 수 있도록 합니다.

1. fetch API 기본 사용법

1.1 기본 문법

fetch 메서드는 첫 번째 인수로 URL을 받고, 두 번째 인수로 옵션 객체를 받아 HTTP 요청을 수행합니다. 기본적으로 GET 요청을 수행하며, POST, PUT, DELETE 등의 다른 HTTP 메서드를 사용할 수 있습니다.

fetch(url, options)
  .then(response => response.json()) // 응답을 JSON으로 변환
  .then(data => console.log(data))    // 데이터 처리
  .catch(error => console.error('Error:', error)); // 에러 처리
  • url: 요청할 URL
  • options (선택 사항): 요청의 세부 사항을 설정하는 객체

2. fetch API 주요 메서드 및 옵션

2.1 기본 GET 요청

기본적인 GET 요청을 보내는 예제입니다.

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

2.2 POST 요청

POST 요청을 보내는 방법입니다. POST 요청 시, body에 데이터를 포함할 수 있습니다.

fetch('https://api.example.com/data', {
  method: 'POST', // HTTP 메서드
  headers: {
    'Content-Type': 'application/json' // 요청의 내용 형식
  },
  body: JSON.stringify({
    key1: 'value1',
    key2: 'value2'
  }) // 전송할 데이터
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

2.3 PUT 요청

PUT 요청을 보내는 방법입니다. PUT 요청은 서버의 자원을 업데이트할 때 사용합니다.

fetch('https://api.example.com/data/1', {
  method: 'PUT', // HTTP 메서드
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    key1: 'newValue1',
    key2: 'newValue2'
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

2.4 DELETE 요청

DELETE 요청을 보내는 방법입니다. DELETE 요청은 서버에서 자원을 삭제할 때 사용합니다.

fetch('https://api.example.com/data/1', {
  method: 'DELETE' // HTTP 메서드
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

3. 응답 처리

3.1 응답 상태 확인

응답 객체의 ok, status, statusText 속성을 통해 요청의 성공 여부와 상태 코드를 확인할 수 있습니다.

fetch('https://api.example.com/data')
  .then(response => {
    if (!response.ok) {
      throw new Error(`HTTP error! Status: ${response.status}`);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

3.2 응답 본문 읽기

응답 본문을 읽는 다양한 방법:

  • response.json(): JSON 형식으로 응답 본문을 읽습니다.
  • response.text(): 텍스트 형식으로 응답 본문을 읽습니다.
  • response.blob(): 바이너리 대용량 객체로 응답 본문을 읽습니다.
  • response.formData(): FormData 객체로 응답 본문을 읽습니다.
  • response.arrayBuffer(): 원시 이진 데이터 버퍼로 응답 본문을 읽습니다.
fetch('https://api.example.com/data')
  .then(response => response.json()) // JSON 형식으로 읽기
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

fetch('https://example.com/file')
  .then(response => response.blob()) // Blob 형식으로 읽기
  .then(blob => {
    const url = URL.createObjectURL(blob);
    console.log(url);
  })
  .catch(error => console.error('Error:', error));

4. fetch API의 추가 옵션

4.1 요청 헤더

요청 헤더를 설정하는 방법입니다.

fetch('https://api.example.com/data', {
  method: 'GET',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer token'
  }
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

4.2 요청 본문

POST, PUT 등의 요청에서 본문을 설정할 수 있습니다.

fetch('https://api.example.com/data', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    key1: 'value1',
    key2: 'value2'
  })
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

4.3 mode 옵션

요청 모드를 설정하는 옵션입니다.

  • cors: 기본값, CORS 요청을 허용합니다.
  • no-cors: CORS 요청을 허용하지 않습니다.
  • same-origin: 동일 출처에서만 요청을 허용합니다.
fetch('https://api.example.com/data', {
  mode: 'cors' // 또는 'no-cors', 'same-origin'
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

4.4 credentials 옵션

인증 정보 포함 여부를 설정하는 옵션입니다.

  • same-origin: 동일 출처에서만 인증 정보를 포함합니다.
  • include: 모든 요청에 인증 정보를 포함합니다.
  • omit: 인증 정보를 포함하지 않습니다.
fetch('https://api.example.com/data', {
  credentials: 'include' // 또는 'same-origin', 'omit'
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

5. fetch API의 실제 사용 예

5.1 데이터 가져오기

fetch('https://api.example.com/users')
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok');
    }
    return response.json();
  })
  .then(users => {
    users.forEach(user => console.log(user.name));
  })
  .catch(error => console.error('Fetch error:', error));

5.2 파일 업로드

const formData = new FormData();
formData.append('file', fileInput.files[0]);

fetch('https://api.example.com/upload', {
  method: 'POST',
  body: formData
})
  .then(response => response.json())
  .then(result => console.log(result))
  .catch(error => console.error('Upload error:', error));

5.3 폼 데이터 제출

const formData = new FormData(document.querySelector('form'));

fetch('https://api.example.com/submit', {
  method: 'POST',
  body: formData
})
  .then(response => response.json())
  .then(result => console.log(result))
  .catch(error => console.error('Form submission error:', error));

결론

Fetch API는 네트워크 요청을 수행하고 응답을 처리하는 강력하고 유연한 방법을 제공합니다. 프로미스를 기반으로 한 fetch 메서드는 비동기 처리를 간결하게 구현할 수 있도록 하며, 다양한 옵션과 메서드를 통해 다양한 네트워크 요청 시나리오를 처리할 수 있습니다. 이를 통해 현대적인 웹 애플리케이션의 클라이언트 측 데이터 통신을 효율적으로 다룰 수 있습니다.


Leave a Reply

Your email address will not be published. Required fields are marked *