Node.js 시작하기 (2) - 웹페이지 보내주려면 (라우팅)

funfungun·2024년 9월 4일
0
post-thumbnail

오늘은 여러가지 페이지를 만들려면 어떻게 해야되는지 알아봅시다.


  1. 누가 /news 로 접속하면 오늘의 뉴스를 보여주도록 해봅시다.기존의 코드에 경로를 추가해줍시다.

    //server.js
    
    const express = require("express");
    const app = express();
    
    app.listen(8080, () => {
      console.log("http://localhost:8080 에서 서버 실행중");
    });
    
    app.get("/", (req, res) => {
      res.send("Hello World!");
    });
    
    app.get("/news", (req, res) => {
      res.send("Hello News!");
    });

  1. 이전에 실행중인 서버가 있다면 터미널에서 command + C 를 눌러서 종료해주고, 다시 node server.js 를 입력하여 실행해줍니다. 이후, 서버 url 에 /news 만 붙여서 접속해봅시다.

  1. 이제 단순한 문장이 아닌 html 페이지를 만들고 싶다면, index.html 을 다음과 같이 만들어 봅시다. !를 누르고 tab 키를 누르면 기본 템플릿이 등장합니다.

    <!-- index.html -->
    
    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
      </head>
      <body>
        <h1>Home Page</h1>
      </body>
    </html>

  1. 기본 경로를 들어갔을 때 방금 만들었던 웹 페이지가 보이게 하려면, server.js 를 다음과 같이 수정하면 됩니다. 여기서 __dirname 은 현재 프로젝트의 절대 경로를 의미합니다.

    //server.js
    
    const express = require("express");
    const app = express();
    
    app.listen(8080, () => {
      console.log("http://localhost:8080 에서 서버 실행중");
    });
    
    app.get("/", (req, res) => {
      res.sendFile(__dirname + "/index.html");
    });
    
    app.get("/news", (req, res) => {
      res.send("Hello News!");
    });

  1. 이제 다시 http://localhost:8080 에 들어가보면 만들었던 html 파일이 잘 보이는 것을 확인할 수 있습니다.

지금까지 서버에서 여러가지 페이지를 만들려면 어떻게 해야하는지 알아보았습니다. 다음 시간에는 웹페이지에 디자인을 넣으려면 어떻게 해야하는지 알아봅시다.

profile
Commercial Art

0개의 댓글