오늘은 여러가지 페이지를 만들려면 어떻게 해야되는지 알아봅시다.
누가 /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!");
});
이제 단순한 문장이 아닌 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>
기본 경로를 들어갔을 때 방금 만들었던 웹 페이지가 보이게 하려면, 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!");
});
지금까지 서버에서 여러가지 페이지를 만들려면 어떻게 해야하는지 알아보았습니다. 다음 시간에는 웹페이지에 디자인을 넣으려면 어떻게 해야하는지 알아봅시다.