본문 바로가기
Do it Node.js/EJS BackEnd

8. 라우팅

by 갱생angel 2024. 3. 1.

라우팅 : 클라이언트에서 요청한 URL에 따라 다른 내용을 표시하는 것

 

ch04 - <routing.js> : 각 url 마다 화면에 출력되는 내용 달리 하기

res.statusCode : 상태 코드를 설정

※텍스트 문자열을 한 번만 보낸다면 res.write 함수를 쓰지 않고 res.end로 처리 가능

const http = require("http");

const server = http.createServer((req, res) => {
  const { method, url } = req; //요청 메서드, url 가져오기
  res.setHeader("Content-Type", "text/plan");

  if (method === "GET" && url === "/home") { //메서드가 GET, url이 /home 일 경우
    res.statusCode = 200;
    res.end("HOME");
  } else if (method === "GET" && url === "/about") { //메서드가 GET, url이 /about 일 경우
    res.statusCode = 200;
    res.end("ABOUT");
  } else { //그 외
    res.statusCode = 404;
    res.end("NOT FOUND");
  }
});

server.listen(3000, () => {
  console.log("3000 포트에서 서버 실행 중");
});

'Do it Node.js > EJS BackEnd' 카테고리의 다른 글

10. Express  (0) 2024.03.03
9. Node 비동기 처리  (0) 2024.03.01
7. HTTP 모듈  (0) 2024.02.29
6. 버퍼, 스트림, 파이프  (0) 2024.02.28
5. fs 모듈  (0) 2024.02.27