TIL/Today I Learned

[TIL] 23.08.02 Today I Learned / node.js 웹서버 제작

임성장 2023. 8. 2. 16:03
728x90

요약: node.js을 사용해서 간단한 웹서버 만들기

일시: 23.08.02

장소: 더휴먼컴퓨터아트아카데미

배운 점:

var http = require("http");
var hostname = "127.0.0.1";
var port = "8080";

const server = http.createServer(function (req, res) {
    const path = req.url;
    const method = req.method;

    if (path === "/products") {
        if (method === "GET") {
            res.writeHead(200, { "Content-Type": "application/json" });
            const products = JSON.stringify([
                {
                    name: "독버섯조명",
                    price: 89000,
                    seller: "유니스",
                },
            ]);
            res.end(products);
        } else if (method === "POST") {
            res.end("생성되었습니다.");
        }
    }
    res.end("Good bye");
});

server.listen(port, hostname);

console.log("server on");

라이브러리 및 변수 선언

var http = require("http")

  • Node.js의 http 모듈을 불러오기
  • 웹 서버를 생성하고 웹 요청과 응답을 처리하는 기능을 제공

var hostname = "127.0.0.1";

  • 서버를 실행할 호스트 이름 또는 IP 주소를 지정
  • 여기서는 로컬 호스트를 사용

var port = "8080";

  • 서버가 실행될 포트 번호를 지정

 

 

서버 생성

const server = http.createServer(function (req, res) { ... });

  • http.createServer() 함수를 사용하여 웹 서버를 생성
  • 요청(req)과 응답(res) 객체를 처리하는 콜백 함수를 인수로 받기

 

요청 및 응답 처리

const path = req.url;

  • 요청의 URL 주소를 가져오기

const method = req.method;

  • 요청의 HTTP 메서드(GET, POST 등)를 가져오기

 

라우팅 및 응답 전송

if (path === "/products") { ... }

  • 요청의 URL이 "/products"일 때 블록 안의 코드를 실행

if (method === "GET") { ... }

  • GET 메서드로 요청이 올 때 블록 안의 코드를 실행

res.writeHead(200, { "Content-Type": "application/json" })

  • 응답 헤더를 설정
  • 여기서는 JSON 형식의 응답을 전송할 것이라고 명시

const products = JSON.stringify([...])

  • 하나의 상품 객체를 배열로 감싸고 JSON 형식으로 변환하여 변수에 저장

res.end(products)

  • JSON 형식의 상품 정보를 응답으로 전송

 

서버 실행

server.listen(port, hostname);

  • 서버를 지정된 포트와 호스트로 바인딩하여 실행

 

 

부족한 점:

728x90