작성일/수정일
2024-01-28 16:42:37 / 2024-01-28 16:42:37
fetch()
함수는 첫번째 인자로 URL, 두번째 인자로 옵션 객체를 받고, Promise 타입의 객체를 반환합니다.
반환된 객체는, API 호출이 성공했을 경우에는 응답(response) 객체를 resolve하고, 실패했을 경우에는 예외(error) 객체를 reject합니다.
옵션(options) 객체에는 HTTP 방식(method), HTTP 요청 헤더(headers), HTTP 요청 전문(body) 등을 설정해줄 수 있습니다. 응답(response) 객체로 부터는 HTTP 응답 상태(status), HTTP 응답 헤더(headers), HTTP 응답 전문(body) 등을 읽어올 수 있습니다.
fetch(url, options)
.then((response) => console.log("response:", response))
.catch((error) => console.log("error:", error));
GET(default)
fetch("URL").then((response) =>
console.log(response)
);
POST
fetch("URL", {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({ /* param */
title: "Test",
body: "I am testing!",
userId: 1,
}),
}).then((response) => console.log(response));
PUT(Update)
fetch("url", {
method: "PUT",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
title: "Test",
body: "I am testing!",
userId: 1,
}),
})
.then((response) => response.json())
.then((data) => console.log(data));