[자바스크립트(Java Script)]8. Fetch API를 활용한 REST API 통신 기초 (GET, POST, PUT, DELETE 요청)

손영민's avatar
Apr 14, 2025
[자바스크립트(Java Script)]8. Fetch API를 활용한  REST API 통신 기초 (GET, POST, PUT, DELETE 요청)
<!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

sson17