[NodeJS] 3장 라우팅 구현, HTTP 서버만들기

1. Node.js HTTP 서버 기본 설정

Node.js에서 HTTP 서버를 만드는 것은 매우 간단하며, http 모듈을 사용해 서버를 생성하고 요청을 처리할 수 있습니다.

프로젝트 폴더에 server.js 파일을 생성해 아래 코드를 추가합니다.

yarn add http
// server.js
const http = require("http");

// 서버 생성
const server = http.createServer((req, res) => {
  // 응답 헤더 설정
  res.writeHead(200, { "Content-Type": "text/plain" });
  res.end("Hello, World!\n");
});

// 서버 실행
const PORT = 3000;
server.listen(PORT, () => {
  console.log(`server is running http://localhost:${PROT}`);
});

2. 라우팅 구현

HTTP 서버에 다양한 경로에 대한 라우팅을 추가할 수 있습니다. 이를 통해서 요청된 URL에 따른 다른 응답을 반환할 수 있습니다. 아래 코드는 기본 서버에 라우팅을 추가하는 코드입니다.

// routing.js
const http = require("http");

// 서버 생성
const server = http.createServer((req, res) => {
  // URL 요청에 따라 라우팅
  if (req.url === "/") {
    res.writeHead(200, { "Content-Type": "text/plain" });
    res.end("This HomePage \n");
  } else if (req.url === "/about") {
    res.writeHead(200, { "Content-Type": "text/plain" });
    res.end("This is About \n");
  } else if (req.url === "/contract") {
    res.writeHead(200, { "Content-Type": "text/plain" });
    res.end("This is Contract");
  } else {
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.end("404 Not Found");
  }
});

// 서버 실행
const PORT = 3000;
server.listen(PORT, () => {
  console.log(`server is running: ${PORT}`);
});

 

서버를 실행한 후, 다음 브라우저 URL에 접속하면, 서로 다른 결과를 확인 할 수 있습니다.

  • http://localhost:3000/ - "This is HomePage"
  • http://localhost:3000/about - "This is About"
  • http://localhost:3000/contract - "This is Contract"
  • http://localhost:3000/asdnasd - "404 Not Found"

3.정리

Node.js의 기본 HTTP 서버를 설정해 라우팅하는 방법을 배웠습니다. 이 기본적 구조를 바탕으로 더욱 복잡한 웹 애플리케이션을 구축할 수 있습니다. 필요에 따라서 Express.js와 같은 웹 프레임워크를 사용하면 라우팅과 미들웨어 처리가 더욱 수월해집니다.


 

GitHub - nodeJsroom/node-js-bloging

Contribute to nodeJsroom/node-js-bloging development by creating an account on GitHub.

github.com

 

LIST