[JavaScript] fetch 다시 보기

snowballnote·2026년 10월 2일

알림 관리 화면에서 수신자 목록을 불러오고
등록이나 비활성화를 할 때 fetch를 사용했다.

const response = await fetch(url, options);

fetch는 브라우저에서 HTTP 요청을 보낼 때 쓰는 함수다.

GET은 옵션 없이도 가능하다.

const subscribers = await requestJson(
    "/api/notification-subscribers"
);

등록할 때는 POST.

await requestJson(API_URL, {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        name: elements.name.value.trim(),
        email: elements.email.value.trim(),
        notificationType: elements.notificationType.value
    })
});

비활성화는 PATCH.

await requestJson(
    `${API_URL}/${subscriber.id}/disable`,
    {
        method: "PATCH"
    }
);

이번에 다시 본 건
fetch가 404나 500이라고 자동으로 예외를 던지는 건 아니라는 점.

const response = await fetch(url, options);

if (!response.ok) {
    throw new ApiError(
        response.status,
        body?.message || "요청을 처리하지 못했습니다."
    );
}

그래서 response.ok를 직접 확인했다.

응답 JSON도 따로 꺼내야 한다.

const body = await response.json();

정리하면 이번 화면에서는

fetch
→ 서버에 요청

await response.json()
→ 응답 JSON 읽기

response.ok
→ 요청 성공 여부 확인

이렇게 사용했다.

그리고 등록이나 비활성화가 끝나면
다시 목록을 조회했다.

await loadSubscribers();

즉 화면에서 직접 데이터를 들고 복잡하게 수정하기보다
서버 반영 후 다시 조회해서 최신 상태를 보여주는 방식으로 만들었다.

profile
개발자로 이 험난한 세상 살아가기

0개의 댓글