[자바스크립트] 8. Methods

문정준's avatar
Apr 02, 2025
[자바스크립트] 8. Methods

1. HTTP Methods

  • JSON에서 요청을 넣을 때 사용하는 fetch()
    • 기본 method는 get
    • 이외의 요청일 경우, fetch 내에 id를 작성해서 method, body, headers 등을 작성해야 함
let response = await fetch("uri",{ method: "POST", // GET, POST, PUT, DELETE body: JSON.stringify(JSObject), // Convert JS Object to JSON headers: {"Content-Type": "application/json"} // Body explaination // Content-Type : MIME Type // Must attach when body exists (POST, PUT) });
 
 

2. Fetch Options

  • GET, DELETE의 methods에는 body 데이터가 필요 없음
    • body 데이터를 설명할 headers도 필요 없음
    • 즉, body 데이터가 달리면 headers도 함께 작성
    • 서버 측에서 content-type을 보고 body를 파싱하거나, 들어올 데이터 타입을 정해서 파싱할 수도 있음
      • 서버 및 프레임워크마다 동작이 다르므로, body가 달리면 header는 무조건 포함할 것
        • Convention
notion image
 

Body에 JSON.stringify()를 담을 때 주의사항

  • key는 쌍따옴표로 감싸도 되고, 안 감싸도 됨 (JS Object는 둘 다 인식)
  • 문자열을 통해 직접 데이터를 만들 경우, key를 문자열로 감싸면 서버에서 인식하지 않을 수 있음
 
notion image
 
notion image
 

Example

<!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"> <input type="text" id="content" placeholder="content"> <input type="text" id="author" placeholder="author"> <button type="button" onclick="write()">게시글쓰기</button> </form> <script> async function write() { 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>
 
  • GET
notion image
 
  • POST
    • response의 body가 null : 성공했다는 Status만 전송됨
    • 이를 확인하기 위해서는 직접 api 확인이 필요
notion image
notion image
 
  • PUT
    • POST와 마찬가지로 response의 body가 null
    • 직접 api 확인 필요
notion image
 
  • DELETE
    • POST, PUT과 마찬가지로 response의 body가 null
    • DELETE 요청은 id만 필요하므로 request의 body도 null
notion image
 
  • Button onclick event : write()
    • POST 요청 발생
    • onclick 이벤트 : form 태그 내에서 submit이 발동되면 우선 순위에서 밀려남
notion image
notion image
 
Share article

sxias