😎 κ³΅λΆ€ν•˜λŠ” μ§•μ§•μ•ŒνŒŒμΉ΄λŠ” μ²˜μŒμ΄μ§€?

[http λͺ¨λ“ˆλ‘œ μ„œλ²„] (2) REST둜 RESTful ν•œ μ›Ή μ„œλ²„ λ§Œλ“€κΈ° λ³Έλ¬Έ

πŸ‘©‍πŸ’» λ°±μ—”λ“œ(Back-End)/Node js

[http λͺ¨λ“ˆλ‘œ μ„œλ²„] (2) REST둜 RESTful ν•œ μ›Ή μ„œλ²„ λ§Œλ“€κΈ°

μ§•μ§•μ•ŒνŒŒμΉ΄ 2023. 4. 16. 01:59
728x90
λ°˜μ‘ν˜•

<λ³Έ λΈ”λ‘œκ·ΈλŠ” Node.js κ΅κ³Όμ„œλ₯Ό μ°Έκ³ ν•΄μ„œ κ³΅λΆ€ν•˜λ©° μž‘μ„±ν•˜μ˜€μŠ΅λ‹ˆλ‹€ :-)>

 

πŸŽ€ REST (REpresentational State Transfer)

: μ„œλ²„μ˜ μžμ›μ„ μ •μ˜ν•˜κ³  μžμ›μ— λŒ€ν•œ μ£Όμ†Œλ₯Ό μ§€μ •ν•˜λŠ” 방법

 

πŸŽ€ RESTful

: RESTλ₯Ό λ”°λ₯΄λŠ” μ„œλ²„

 

πŸŽ€ HTTP μš”μ²­ λ©”μ„œλ“œ

GET : μ„œλ²„ μžμ›μ„ κ°€μ Έμ˜€κ³ μž ν•  λ•Œ μ‚¬μš©

POST : μ„œλ²„μ— μžμ›μ„ μƒˆλ‘œ 등둝할 λ•Œ μ‚¬μš©

PUT : μ„œλ²„μ˜ μžμ›μ„ μš”μ²­μ— λ“€μ–΄ μžˆλŠ” μžμ›μœΌλ‘œ μΉ˜ν™˜ν•  λ•Œ μ‚¬μš©

PATCH : μ„œλ²„ μžμ›μ˜ μΌλΆ€λ§Œ μˆ˜μ •ν•  λ•Œ μ‚¬μš©

DELETE : μ„œλ²„μ˜ μžμ›μ„ μ‚­μ œ ν•  λ•Œ μ‚¬μš©

OPTIONS : μš”μ²­μ„ ν•˜κΈ° 전에 톡신 μ˜΅μ…˜ μ„€λͺ…ν•˜κΈ° μœ„ν•΄ μ‚¬μš©

 

πŸŽ€ REST둜 RESTful ν•œ μ›Ή μ„œλ²„ λ§Œλ“€κΈ° 

🌿 about.html

<!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>RESTful SERVER</title>
</head>

<body>
  <nav>
    <a href="/">Home</a>
    <a href="/about">About</a>
  </nav>
  <div>
    <h2>μ†Œκ°œ νŽ˜μ΄μ§€</h2>
    <p>μ‚¬μš©μž 이름을 λ“±λ‘ν•˜μ„Έμš”!</p>
  </div>
</body>
</html>

 

🌿 restFront.html

<!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>RESTful SERVER</title>
</head>

<body>
  <nav>
    <a href="/">Home</a>
    <a href="/about">About</a>
  </nav>
  <div>
    <form id="form">
      <input type="text" id="username">
      <button type="submit">등둝</button>
    </form>
  </div>
  <div id="list"></div>
  <script src="https://unpkg.com/axios/dist/axios.min.js"></script>
  <script src="./restFront.js"></script>
</body>

</html>

 

🌿 restFront.js

// λ‘œλ”© μ‹œ μ‚¬μš©μž 정보 κ°€μ Έμ˜€κΈ°
async function getUser() {
  try {
    const res = await axios.get("/users");
    const users = res.data;
    const list = document.getElementById("list");
    list.innerHTML = "";

    // μ‚¬μš©μžλ§ˆμž 반볡적으둜 ν™”λ©΄ ν‘œμ‹œ 및 이벀트 μ—°κ²°
    Object.keys(users).map(function (key) {
      const userDiv = document.createElement("div");
      const span = document.createElement("span");
      span.textContent = users[key];
      const edit = document.createElement("button");
      edit.textContent = "μˆ˜μ •";
      edit.addEventListener("click", async () => {
        const name = prompt("λ°”κΏ€ 이름을 μž…λ ₯ν•˜μ„Έμš”");
        if (!name) {
          return alert("이름을 λ°˜λ“œμ‹œ μž…λ ₯!");
        }
        try {
          await axios.put("/user/" + key, { name });
          getUser();
        } catch (err) {
          console.error(err);
        }
      });

      const remove = document.createElement("button");
      remove.textContent = "μ‚­μ œ";
      remove.addEventListener("click", async () => {
        try {
          await axios.delete("/user/" + key)
          getUser();
        } catch (err) {
          console.error(err);
        }
      });
      userDiv.appendChild(span);
      userDiv.appendChild(edit);
      userDiv.appendChild(remove);
      list.appendChild(userDiv);
      console.log(res.data);
    });
  } catch (err) {
    console.error(err);
  }
}

// ν™”λ©΄ λ‘œλ”© μ‹œ getUser 호좜
window.onload = getUser;
// 폼 제좜 μ‹œ μ‹€ν–‰
document.getElementById("form").addEventListener("submit", async (e) => {
  e.preventDefault();
  const name = e.target.username.value;
  if (!name) {
    return alert("이름을 λ°˜λ“œμ‹œ μž…λ ₯!");
  }
  try {
    await axios.post("/user", { name });
    getUser();
  } catch (err) {
    console.log(err);
  }
  e.target.username.value = "";
});

 

🌿 restFront.css

a {color:blue; text-decoration: none;}

 

🌿 restServer.js

const http = require("http");
const fs = require("fs").promises;

const users = {};

http.createServer(async (req, res) => {
  try {
    console.log(req.method, req.url);
    if (req.method == "GET") {
      if (req.url === "/") {
        const data = await fs.readFile("./restFront.html");
        res.writeHead(200, { "Content-type": "text/html : charset=utf-8" });
        return res.end(data);
      } else if (req.url === "/about") {
        const data = await fs.readFile("./about.html");
        res.writeHead(200, { "Content-type": "text/html : charset=utf-8" });
        return res.end(data);
      } else if (req.url === "/users") {
        res.writeHead(200, { "Content-type": "text/plain : charset=utf-8" });
        return res.end(JSON.stringify(users));
      }
      try {
        const data = await fs.readFile(`.${req.url}`);
        return res.end(data);
      } catch (err) {
        // 404 not found
      }
    } else if (req.method === "POST") {
      if (req.url === "/user") {
        let body = "";
        // μš”μ²­μ˜ bodyλ₯Ό stream ν˜•νƒœλ‘œ λ°›μŒ
        req.on("data", (data) => {
          body += data;
        });

        return req.on("end", () => {
          console.log("POST λ³Έλ¬Έ(body) : ", body);
          const { name } = JSON.parse(body);
          const id = Date.now();
          users[id] = name;
          res.writeHead(201);
          res.end("등둝 성곡");
        });
      }
    } else if (req.method === "PUT") {
      if (req.url.startsWith("/user/")) {
        const key = req.url.split("/")[2];
        let body = "";
        // μš”μ²­μ˜ bodyλ₯Ό stream ν˜•νƒœλ‘œ λ°›μŒ
        req.on("data", (data) => {
          body += data;
        });
        console.log("hi")
        return req.on("end", () => {
          console.log("PUT λ³Έλ¬Έ(body) : ", body);
          users[key] = JSON.parse(body).name;
          return res.end(JSON.stringify(users));
        });
      }
    } else if (req.method === "DELETE") {
      if (req.url.startsWith("/user/")) {
        const key = req.url.split("/")[2];
        delete users[key];
        return res.end(JSON.stringify(users));
      }
    }
    res.writeHead(404);
    return res.end("NOT FOUND");
  } catch (err) {
    console.error(err);
    res.writeHead(500);
    res.end(err);
  }
})

  .listen(8082, () => {
    console.log("8082번 ν¬νŠΈμ—μ„œ μ„œλ²„ λŒ€κΈ°μ€‘");
  });

 

728x90
λ°˜μ‘ν˜•
Comments