[자바스크립트(Java Script)]8. Fetch API를 활용한 REST API 통신 기초 (GET, POST, PUT, DELETE 요청)
Apr 14, 2025
![[자바스크립트(Java Script)]8. Fetch API를 활용한 REST API 통신 기초 (GET, POST, PUT, DELETE 요청)](https://image.inblog.dev?url=https%3A%2F%2Finblog.ai%2Fapi%2Fog%3Ftitle%3D%255B%25EC%259E%2590%25EB%25B0%2594%25EC%258A%25A4%25ED%2581%25AC%25EB%25A6%25BD%25ED%258A%25B8%28Java%2520Script%29%255D8.%2520Fetch%2520API%25EB%25A5%25BC%2520%25ED%2599%259C%25EC%259A%25A9%25ED%2595%259C%2520%2520REST%2520API%2520%25ED%2586%25B5%25EC%258B%25A0%2520%25EA%25B8%25B0%25EC%25B4%2588%2520%28GET%252C%2520POST%252C%2520PUT%252C%2520DELETE%2520%25EC%259A%2594%25EC%25B2%25AD%29%26logoUrl%3Dhttps%253A%252F%252Finblog.ai%252Finblog_logo.png%26blogTitle%3Dsson17&w=2048&q=75)
Contents
응답 처리<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<h1>fetch get, post, put, delete</h1>
<hr />
<button onclick="get1()">get</button>
<button onclick="post1()">post</button>
<button onclick="put1()">put</button>
<button onclick="delete1()">delete</button>
<form>
<input type="text" id="title" placeholder="title" /><br />
<input type="text" id="content" placeholder="content" /><br />
<input type="text" id="author" placeholder="author" /> <br />
<button type="button" onclick="write1()">게시글쓰기</button>
</form>
<script>
async function write1() {
let requestBody = {
title: document.querySelector("#title").value,
content: document.querySelector("#content").value,
author: document.querySelector("#author").value,
};
let response = await fetch("http://localhost:8080/api/boards", {
method: "post",
body: JSON.stringify(requestBody),
headers: { "Content-Type": "application/json" },
});
let responseBody = await response.json();
console.log(responseBody);
}
async function get1() {
let response = await fetch("http://localhost:8080/api/boards/1", {
method: "get",
});
let responseBody = await response.json();
console.log(responseBody);
}
async function post1() {
let requestBody = {
title: "제목9",
content: "내용9",
author: "ssar",
};
let response = await fetch("http://localhost:8080/api/boards", {
method: "post",
body: JSON.stringify(requestBody),
headers: { "Content-Type": "application/json" },
});
let responseBody = await response.json();
console.log(responseBody);
}
async function put1() {
let requestBody = {
title: "제목11",
content: "내용11",
author: "ssar",
};
let response = await fetch("http://localhost:8080/api/boards/1", {
method: "put",
body: JSON.stringify(requestBody),
headers: { "Content-Type": "application/json" },
});
let responseBody = await response.json();
console.log(responseBody);
}
async function delete1() {
let response = await fetch("http://localhost:8080/api/boards/1", {
method: "delete",
});
let responseBody = await response.json();
console.log(responseBody);
}
</script>
</body>
</html>
1. Fetch API 기본 구조
Fetch API의 기본 형태는 다음과 같습니다:
fetch(url, options)
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
또는 async/await를 사용하면:
async function fetchData() {
try {
const response = await fetch(url, options);
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}
2. HTTP 메서드별 요청 방법
GET 요청
fetch(url, { method: "get" })
GET 요청은 서버에서 데이터를 조회할 때 사용합니다. URL의 쿼리 파라미터를 통해 데이터를 전달할 수 있습니다.
POST 요청
fetch(url, {
method: "post",
body: JSON.stringify(데이터),
headers: { "Content-Type": "application/json" }
})
POST 요청은 새로운 리소스를 생성할 때 사용합니다. 요청 본문(body)에 데이터를 JSON 형태로 포함시켜 전송합니다.
PUT 요청
fetch(url, {
method: "put",
body: JSON.stringify(데이터),
headers: { "Content-Type": "application/json" }
})
PUT 요청은 기존 리소스를 수정할 때 사용합니다. POST와 마찬가지로 요청 본문에 데이터를 포함시킵니다.
DELETE 요청
fetch(url, { method: "delete" })
DELETE 요청은 리소스를 삭제할 때 사용합니다. 일반적으로 URL 경로에 삭제할 리소스의 ID를 포함시킵니다.
응답 처리
Fetch API는 Promise를 반환하므로,
.then()
이나 await
을 사용하여 응답을 처리할 수 있습니다. 응답(response)에서 실제 데이터를 추출하기 위해서는 .json()
, .text()
등의 메서드를 사용합니다.const response = await fetch(url);
const data = await response.json(); // JSON 형식의 응답 데이터 추출
Share article