fetch 메서드는 기본적으로 첫 번째 인자로 요청할 URL을 받으며, 기본적으로 HTTP 메소드 중 GET 방식으로 동작합니다.
fetch("https://jsonplaceholder.typicode.com/posts", option)
.then(res => res.json())
.then(data => console.log(data));
fetch를 통해 호출할 경우, 해당 URL로 요청을 보내면 응답 객체(Promise 객체 Response)를 받게 됩니다.
첫 번째 .then에서 이 응답을 받고, res.json() 메서드를 사용하여 JSON 형식으로 파싱한 값을 리턴합니다.
그다음 .then에서 파싱된 데이터를 받아 원하는 처리를 할 수 있습니다.
응답 자료 형태 반환 메서드
이러한 응답 자료 형태 반환 메서드는 한 번만 사용할 수 있습니다.
예를 들어, response.text()를 사용하여 응답을 한 번 가져오면 본문 콘텐츠는 이미 처리된 상태이므로,
이후에 response.json() 등을 호출해도 동작하지 않습니다.
HTTP 요청에는 GET, POST, PUT, DELETE 등 여러 가지가 있습니다.
GET : 존재하는 자원을 요청하는 데 사용됩니다.
fetch("https://jsonplaceholder.typicode.com/posts/1") // posts의 id 1인 엘리먼트를 가져옴
.then((response) => response.json())
.then((data) => console.log(data))
POST : 새로운 자원을 생성할 때 사용됩니다.
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "POST", // POST
headers: { // 헤더 조작
"Content-Type": "application/json",
},
body: JSON.stringify({ // 자바스크립트 객체를 json화 한다.
title: "Test",
body: "I am testing!",
userId: 1,
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
PUT : 존재하는 자원 전체를 변경할 때 사용됩니다.
fetch("https://jsonplaceholder.typicode.com/posts", {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Test" // 아예 title 엘리먼트로 전체 데이터를 바꿈. 마치 innerHTML같이.
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
PATCH : 존재하는 자원의 일부를 변경할 때 사용됩니다.
fetch("https://jsonplaceholder.typicode.com/posts/1", { // posts의 id 1인 엘리먼트를 수정
method: "PATCH",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Test" // title만 바꿈. 나머지 요소는 건들지 않음.
}),
})
.then((response) => response.json())
.then((data) => console.log(data))
DELETE : 존재하는 자원을 삭제할 때 사용됩니다.
fetch("https://jsonplaceholder.typicode.com/posts/1", {
method: "DELETE",
})
.then((response) => response.json())
.then((data) => console.log(data))
await / async 문법으로 보다 가독성을 높일 수 있습니다.
fetch("https://jsonplaceholder.typicode.com/posts", option)
.then(res => res.json())
.then(data => console.log(data));
const getPost = async() => {
let res = await fetch("https://jsonplaceholder.typicode.com/posts", option);
let data = await res.json();
console.log(data);
}
fetch() 함수는 기본적으로 간단하게 사용할 수 있지만, 자주 반복하여 사용하다 보면 코드가 중복될 수 있습니다.
예를 들어, 응답 데이터를 가져오기 위해 매번 response.json()을 호출하거나, 데이터를 전송할 때 HTTP 요청 헤더에 "Content-Type": "application/json"를 일일이 설정해야 합니다.
이러한 반복 작업을 줄이기 위해 헬퍼 함수를 만들어 모듈화해 두면, 나중에 훨씬 편리하게 사용할 수 있습니다.
const fetchData = async (url, options = {}) => {
try {
const response = await fetch(url, {
method: "GET",
...options, // 추가 헤더 또는 옵션을 받아 병합
});
// 요청이 성공적으로 이루어졌는지 확인
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
// JSON 형식으로 응답 처리
const data = await response.json();
return data;
} catch (error) {
console.error("Fetch Error:", error);
return null;
}
};
fetchData("https://jsonplaceholder.typicode.com/posts")
.then(data => {
if (data) {
console.log("Fetched Data:", data);
} else {
console.log("No data returned.");
}
});