BackEnd/NodeJs

NodeJS REST API 구현

3일마다 작심3일 2022. 1. 4. 10:42

REST API란? 

REST 와 API의 합성어입니다.

REST는 통신 체계의 스타일을 규정한 아키텍처입니다.

 

Restful API란?

REST 통신 체계 스타일을 준수한 API입니다.

 

myRestBack.js

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

const users = {}; // 데이터 저장용

http
  .createServer(async (req, res) => {
    try {
      if (req.method === "GET") {
        if (req.url === "/") { 
          const data = await fs.readFile("./myRest.html"); // 메인주소일때는 myRest.html 즉 기본이 되는 메인 html을 내보내준다.
          res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" }); // header 값 넣어주기.
          return res.end(data); // response값을 내보내주고 종료.
        } else if (req.url === "/users") { // url이 users면 GET 요청을 한다.
          res.writeHead(200, {
            "Content-Type": "application/json; charset=utf-8",
          });
          return res.end(JSON.stringify(users)); // users객체를 내보내주고 종료.
        }
        try {
          const data = await fs.readFile(`.${req.url}`); // url주소에 해당하는 파일을 검색해본다.
          return res.end(data); // 검색한 파일을 내보낸다.
        } catch (err) { 
          // 주소에 해당하는 라우트를 못 찾았다는 404 Not Found error 발생
        }
      } else if (req.method === "POST") {
        if (req.url === "/user") { // url은 users로 어떤페이지인지를 나타내준다.
          let body = ""; // 변수 생성
          req.on("data", (data) => { // on이벤트는 이벤트리스너 함수로 생각하면 된다. 콜백으로는 Buffer가 온다.
            console.log("data", data);
            body += data; // body에 버퍼값을 넣어준다.
          });
          return req.on("end", () => { // 이벤트가 끝낫다면?
            const { name } = JSON.parse(body); // body를 json객체로 파싱해준다.
            const id = Date.now(); // id는 임의값으로 넣어준거다.
            users[id] = name; // 키값으로 id를 넣고 value로 body에서 추춣한 받은 값으로 넣어준다.
            res.writeHead(201, { "Content-Type": "text/plain; charset=utf-8" }); // 201은 추가? 한다는 의미의 번호다.
            res.end("ok");
          });
        }
        try {
          const data = await fs.readFile(`.${req.url}`);
          return res.end(data);
        } catch (err) {
          // 주소에 해당하는 라우트를 못 찾았다는 404 Not Found error 발생
        }
      } else if (req.method === "PUT") {
        if (req.url.startsWith("/user/")) { // startWith를 이용해서 url쿼리스트링으로 온 값을 읽어준다.
          let body = ""; 
          req.on("data", (data) => {
            console.log("data", data);
            body += data;
          });
          return req.on("end", () => {
            const { name } = JSON.parse(body);
            const key = req.url.split("/")[2]; // url쿼리스트링 값을 split을 이용하여 받아오고
            users[key] = name; // 해당값을 수정해준다.
            res.writeHead(201, { "Content-Type": "text/plain; charset=utf-8" });
            res.end("ok");
          });
        }
        try {
          const data = await fs.readFile(`.${req.url}`);
          return res.end(data);
        } catch (err) {
            res.end('NOT FOUND')
        }
      } else if (req.method === "DELETE") {
            if (req.url.startsWith("/user/")) {
            const key = req.url.split("/")[2];
            delete users[key];
            res.writeHead(201, { "Content-Type": "text/plain; charset=utf-8" });
            return res.end("ok");
            }
        }
        res.writeHead(404);
        return res.end('NOT FOUND')
    } catch (err) { // 예외처리.
      console.error(err);
      res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8" });
      res.end(err.message);
    }
  })
  .listen(8010, () => {
    console.log("8010번 포트에서 서버 대기 중입니다");
  });

제로초님의 강의에 사용된 코드에서 일부 수정했습니다.

 

이미 주석에서 설명을 다 해버렸네요..

 

출처: 제로초님 인프런 강의

코드 출처: 제로초님 gitHub