RISK IT

[TIL3_23.1.11] Simple API - 유저 회원가입 하기 본문

IT/TIL

[TIL3_23.1.11] Simple API - 유저 회원가입 하기

nomoremystery 2023. 1. 13. 10:22
반응형

SIMPLE API

Node.js에서 제공하는 built-in 모듈인 http를 사용해서 API를 구현해봅니다.

소스코드 분석

const users = [
  {
    id: 1,
    name: "Rebekah Johnson",
    email: "Glover12345@gmail.com",
    password: "123qwe",
  },
  {
    id: 2,
    name: "Fabian Predovic",
    email: "Connell29@gmail.com",
    password: "password",
  },
];
const posts = [
  {
    id: 1,
    title: "간단한 HTTP API 개발 시작!",
    content: "Node.js에 내장되어 있는 http 모듈을 사용해서 HTTP server를 구현.",
    userId: 1,
  },
  {
    id: 2,
    title: "HTTP의 특성",
    content: "Request/Response와 Stateless!!",
    userId: 1,
  },
];
// 회원 정보 및 게시글 정보 입력 (하드코딩)
const http = require("http"); // 1. http 모듈 불러오기
const server = http.createServer(); // 2. 서버 객체 생성(웹 서버 생성)
const httpRequestListener = function (request, response) {
  // 요청 처리를 위한 함수 생성
  const { url, method } = request;

  if (method === "POST") {
    if (url === "/users/signup") {
      let body = "";

      request.on("data", (data) => { // 요청에 "data"가 있으면 ~
        body += data;
      });
      request.on("end", () => { // 요청의 데이터가 모두 받아졌으면 ~
        const user = JSON.parse(body);

        users.push({
          id: user.id,
          name: user.name,
          email: user.email,
          password: user.password,
        });
        response.writeHead(200, { "Content-Type": "application/json" });
        // response 객체의 메서드인 writeHead를 사용하여 응답 헤더를 작성
        // ex) response.write('Hello World!\n'); 하면 컨텐츠 내보내기
        response.end(JSON.stringify({ message: "userCreated" }));
        // response 객체의 메서드인 end를 사용하여 응답 본문을 작성
        // 컨텐츠 출력 완료(응답 종료)
        //'JSON.stringify'는 객체를 JSON 문자열로 변환
        //'JSON.parse'는 JSON 문자열을 객체로 변환
      });
    }
  }
};
server.on("request", httpRequestListener);
// 3. 요청 처리 설정
// server 객체에는 이벤트들이 있는데, .on 메서드를 사용해서 server에 이벤트 연결.
// 여기서는 클라이언트가 요청할 때 발생하는 이벤트인 "request"를 .on을 이용해서 httpRequestListener라는 함수를 연결

const IP = "127.0.0.1";
const PORT = 8000;

server.listen(PORT, IP, function () { // 대기 시작
  console.log(`Listening to request on ip ${IP} & port ${PORT}`); // 콘솔에 출력
}); // 서버 생성해서 잘 실행될 경우 콘솔로그로 찍기
// .listen은 server 객체의 메서드
});
/* NOTE 유저 정보 테스트 입력 값
http -v POST 127.0.0.1:8000/users/signup id=3, name="김테스트", email="test@gmail.com", password="test_password"
 */
// 이렇게 주석 처리 했었으나, 
// -- 1. id name email password 사이의 comma는 빼고 입력해야 함
// -- 2. 숫자로 입력하려면 = 대신 != 으로 입력
반응형