fetch

Joey·2024년 11월 25일

fetch

fetch()는 JavaScript에서 제공하는 HTTP 요청 API로, 서버와 비동기 통신을 간단하게 구현할 수 있습니다.

AJAX의 대체로 설계되었으며, 코드가 간결하고 Promise 기반으로 동작하기 때문에 더 나은 비동기 처리와 체이닝이 가능합니다.

fetch()의 기본 사용법

fetch(url, options)
  .then(response => {
    if (!response.ok) {
      throw new Error('Network response was not ok ' + response.statusText);
    }
    return response.json();
  })
  .then(data => console.log(data))
  .catch(error => console.error('There was a problem with your fetch operation:', error));
  • url: 요청을 보낼 대상의 URL.
  • options: 요청의 메서드, 헤더, 본문 등의 설정(옵션 객체).

fetch()의 특징

  1. Promise 기반
    fetch()는 Promise를 반환하여 비동기 작업을 효율적으로 처리합니다.
    응답의 상태나 데이터는 .then().catch()를 통해 확인합니다.

  2. 기본 메서드는 GET
    요청 메서드(method)를 지정하지 않으면 기본값으로 GET 요청을 보냅니다.

  3. Response 객체 반환
    fetch()는 서버 응답을 포함하는 Response 객체를 반환합니다.
    이 객체에서 데이터(JSON,Text 등)를 추출하려면 추가 작업이 필요합니다.

Response 객체의 주요 메서드

fetch()의 응답으로 반환되는 Response 객체는 아래 메서드로 데이터를 처리할 수 있습니다.

.json(): JSON 형식으로 응답을 파싱합니다.
.text(): 텍스트 형식으로 응답을 처리합니다.
.blob(): Blob 객체로 응답을 반환합니다(이미지, 파일 등).
.arrayBuffer(): 바이너리 데이터를 반환합니다.
.formData(): FormData 형식으로 응답을 반환합니다.

사용예시

get 요청

fetch('https://jsonplaceholder.typicode.com/posts/1')
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

POST 요청

fetch('https://임시코드입니다./posts', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify({
    title: 'foo',
    body: 'bar',
    userId: 1,
  }),
})
  .then(response => response.json())
  .then(data => console.log(data))
  .catch(error => console.error('Error:', error));

옵션 객체의 주요 속성

method: HTTP 메서드 지정 (GET, POST, PUT, DELETE 등).
headers: 요청 헤더를 설정하는 객체.
body: 요청 본문, POSTPUT 요청 시 데이터를 담습니다.
mode: 요청의 모드를 설정(cors, no-cors, same-origin).
credentials: 쿠키 전송 여부 설정(include, same-origin, omit).

CORS와 fetch()

CORS란?
CORS(Cross-Origin Resource Sharing)는 다른 출처(origin)의 리소스에 대한 요청을 허용하거나 거부하는 보안 정책입니다.

fetch()와 CORS
기본적으로 fetch()CORS 정책에 따라 제한됩니다.
서버가 적절한 CORS 헤더(Access-Control-Allow-Origin)를 설정해야 합니다.

에러 처리

fetch()는 네트워크 오류만 catch 블록에서 처리합니다. 응답이 HTTP 에러 코드(예: 404, 500)를 반환해도 Promise는 성공으로 간주되므로 추가 검증이 필요합니다.

fetch('https://임시코드입니다./api')
  .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('Fetch error:', error));

fetch()와 async/await

fetch()는 Promise 기반이므로 async/await을 사용해 비동기 코드를 동기적으로 작성할 수 있습니다.

async function fetchData() {
  try {
    const response = await fetch('https://임시코드입니다./posts/1');
    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const data = await response.json();
    console.log(data);
  } catch (error) {
    console.error('Error:', error);
  }
}

fetchData();
profile
멋쟁이사자처럼 프론트엔드 부트캠프 12기

0개의 댓글