실제 JavaScript 예제로 Fetch API 마스터하기

발행: (2026년 1월 19일 오전 03:37 GMT+9)
4 min read
원문: Dev.to

Source: Dev.to

JavaScript를 진지하게 배우고 있다면, Fetch API는 실제 프론트엔드 개발에 필수적인 핵심 기술입니다. 모든 예제는 무료 가짜 API를 사용합니다: .

1️⃣ 사용자 생성 (POST 요청)

async function createUser(userData) {
  const api_url = 'https://jsonplaceholder.typicode.com/users';

  const res = await fetch(api_url, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(userData),
  });

  const data = await res.json();
  console.log(data);
}

createUser({
  id: crypto.randomUUID(),
  name: 'Md Fahim',
  email: 'mdfahim@gmail.com',
});
  • 실제 사용 사례: 회원가입 양식, 관리자 대시보드, 그리고 새로운 레코드 추가.
  • 참고: JSONPlaceholder는 데이터를 영구 저장하지 않으며, 응답만 시뮬레이션합니다.
async function fetchUsersWithPosts() {
  const api_url = 'https://jsonplaceholder.typicode.com/users';

  const queryParams = { _embed: 'posts' };
  const queryString = new URLSearchParams(queryParams).toString();

  const res = await fetch(`${api_url}?${queryString}`);
  const data = await res.json();
  console.log(data);
}

fetchUsersWithPosts();

URLSearchParams란?
객체를 유효한 쿼리 문자열로 변환합니다. 예: { _embed: 'posts' } → _embed=posts`.

  • 실제 사용 사례: 필터링, 페이지네이션, 정렬, 연관 리소스 포함.

3️⃣ 데이터 업데이트 (PUT vs PATCH)

PUT (전체 업데이트)

async function putUser(data) {
  const res = await fetch('https://jsonplaceholder.typicode.com/users/1', {
    method: 'PUT',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });

  console.log(await res.json());
}

PATCH (부분 업데이트 – 권장)

async function patchUser(data) {
  const res = await fetch(`https://jsonplaceholder.typicode.com/users/${data.id}`, {
    method: 'PATCH',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify(data),
  });

  console.log(await res.json());
}

patchUser({ id: 3, name: 'Alex Smith' });
  • 실제 사용 사례: 프로필 정보, 설정 또는 선호도 업데이트.

4️⃣ 사용자 삭제 (DELETE)

async function deleteUser(userId) {
  const res = await fetch(`https://jsonplaceholder.typicode.com/users/${userId}`, {
    method: 'DELETE',
  });

  console.log(await res.json()); // {}
}

deleteUser(5);

✅ DELETE 응답에서 빈 객체 {}는 정상입니다.

5️⃣ new Request() 로 재사용 가능한 요청

async function adminDashboard(request) {
  const res = await fetch(request);
  const data = await res.json();
  console.log(data);
}

/* Create Request */
const addUser = new Request('https://jsonplaceholder.typicode.com/users', {
  method: 'POST',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Hamza Chy', email: 'hamza@gmail.com' }),
});
adminDashboard(addUser);

/* Update Request */
const updateUser = new Request('https://jsonplaceholder.typicode.com/users/11', {
  method: 'PATCH',
  headers: { 'Content-Type': 'application/json' },
  body: JSON.stringify({ name: 'Hamza Chowdhury' }),
});
adminDashboard(updateUser);

/* Delete Request */
const deleteUser11 = new Request('https://jsonplaceholder.typicode.com/users/11', {
  method: 'DELETE',
});
adminDashboard(deleteUser11);

new Request() 를 사용하는 이유는?

  • 더 깔끔한 아키텍처
  • 재사용 가능한 요청 객체
  • 미들웨어‑스타일 패턴
  • 대규모 애플리케이션에 더 적합

6️⃣ AbortController 로 요청 중단하기

let controller; // will hold the AbortController instance

async function downloadFile() {
  controller = new AbortController();

  const res = await fetch('./download/file.txt', {
    signal: controller.signal,
  });

  const blob = await res.blob();
  const url = URL.createObjectURL(blob);

  const a = document.createElement('a');
  a.href = url;
  a.download = 'file.txt';
  a.click();

  URL.revokeObjectURL(url);
}

function abortDownload() {
  controller.abort('User cancelled download');
}
  • 실제 사용 사례: 검색 요청 취소, 파일 다운로드 중단, 레이스 컨디션 방지.
Back to Blog

관련 글

더 보기 »

Axios

!Axios용 표지 이미지 https://media2.dev.to/dynamic/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com...

React 앱의 기본

소개 오늘은 React 앱을 생성할 때 보이는 파일과 폴더의 이유와 사용 방법을 살펴보겠습니다. !React app structurehttps:/...