fetch API
페이지 정보
작성자
DocsArchives
작성일
2025.09.07 19:42
본문
서버와 데이터를 주고받는 표준 방식
웹 개발에서 가장 중요한 작업 중 하나는 서버와의 통신입니다. 과거에는 XMLHttpRequest(XHR)를 사용했지만, 문법이 복잡하고 직관적이지 않았습니다. 이를 대체하는 것이 fetch API입니다.
기본 사용법
fetch("https://jsonplaceholder.typicode.com/posts/1") .then((response) => response.json()) .then((data) => console.log(data)) .catch((error) => console.error("에러:", error));이렇게 하면 API에서 JSON 데이터를 불러와 출력할 수 있습니다.
async/await와 함께 쓰기
async function loadPost() { try { const res = await fetch("https://jsonplaceholder.typicode.com/posts/1"); const data = await res.json(); console.log(data); } catch (err) { console.error("에러 발생:", err); }}이 방식은 에러 처리까지 깔끔하게 할 수 있습니다.
POST 요청 보내기
fetch("https://jsonplaceholder.typicode.com/posts", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ title: "새 글", body: "내용", userId: 1 })}).then(res => res.json()).then(data => console.log(data));fetch API는 직관적이고 강력한 표준 도구입니다. REST API, GraphQL, JSON 데이터를 다룰 때 반드시 알아야 할 기술입니다.
태그
댓글 0