REST API(2)

이시원·2022년 7월 10일

바닐라 JS - 기타

목록 보기
2/7
post-thumbnail

GET 요청

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      // 전체 데이터 조회
      fetch("http://localhost:3000/comments")
        .then((response) => response.json())
        .then((json) => console.log(json));

      // id로 조회
      fetch("http://localhost:3000/comments/1")
        .then((response) => response.json())
        .then((json) => console.log(json));

      // query로 postId = 1로 조회
      fetch("http://localhost:3000/comments?postId=1")
        .then((response) => response.json())
        .then((json) => console.log(json));
    </script>
  </body>
</html>

POST 요청

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      fetch("http://localhost:3000/posts", {
        method: "POST", // HTTP 요청 방법
        body: JSON.stringify({
          // 전송할 데이터
          title: "The Great",
          author: "Jeremy",
        }),
        headers: {
          // 헤더 값 정의
          "content-type": "application/json; charset=UTF-8", // content-type 정의
        },
      })
        .then((response) => response.json())
        .then((json) => console.log(json));
    </script>
  </body>
</html>


PUT 요청

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      fetch("http://localhost:3000/posts/2", {
        method: "PUT",
        body: JSON.stringify({
          id: 2,
          title: "The Great Jeremy",
          author: "Jeremy",
        }),
        headers: {
          "content-type": "application/json; charset=UTF-8",
        },
      })
        .then((response) => response.json())
        .then((json) => console.log(json));
    </script>
  </body>
</html>



DELETE 요청

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    <script>
      fetch("http://localhost:3000/posts/2", { method: "DELETE" });
    </script>
  </body>
</html>


profile
코딩공부

0개의 댓글