이번에는 express 모듈을 통해 만든 서버에 접속하면 html 페이지를 보여주도록 하겠습니다.
시작
프로젝트 폴더에 html 페이지를 관리하는 views 와 script 파일을 관리하는 js 라는 폴더를 만들었습니다.
views 폴더에 home.html 파일을 생성하고 다음과 같이 작성합니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Chatting</title>
</head>
<body>
<header>Chatting Web Page</header>
<main>
<h2>Welcome</h2>
</main>
</body>
<script type="text/javascript" src="/src/js/app.js"></script>
</html>
다음으로 js 폴더 안에 app.js 라는 파일을 만들고 다음과 같이 alert 를 통해 경고창을 띄우도록 합니다.
alert("hi");
server.js 파일에 app.get() 을 통해 / 로 접속했을 경우home.html 파일을 보내줍니다.
/ 외의 url 은 모두 / 로 리다이렉트를 통해 접속하도록 합니다.
import express from "express";
const app = express();
app.get("/", (req, res) => res.sendFile(__dirname + "/views/" + "home.html"));
app.get("/*", (req, res) => res.redirect("/"));
const handleListen = () => {
console.log("Server Start");
};
app.listen(3000, handleListen);
실행
localhost:3000 을 브라우저에 입력해서 접속을 해보면
html 파일은 볼 수 있지만 script 파일은 실행되지 않습니다.
이는 html 파일이 script 파일을 연결할때 src = "/src/js/app.js" 로 연결을 했는데 이 경로는 프로젝트 안의 경로이며,
html 파일은 서버를 통해 전송받기 때문에 서버에 script 파일의 위치를 등록하고 이를 통해 script 를 가져와야 합니다.
수정
다음과 같이 server.js 에 app.use() 를 통해 프로젝트의 js 폴더를 등록해줍니다.
import express from "express";
const app = express();
app.use("/js", express.static(__dirname + "/js"));
app.get("/", (req, res) => res.sendFile(__dirname + "/views/" + "home.html"));
app.get("/*", (req, res) => res.redirect("/"));
const handleListen = () => {
console.log("Server Start");
};
app.listen(3000, handleListen);
이제 프로젝트의 "/src/js" 폴더를 "/js" 를 통해 접근할 수 있습니다.
home.html 파일의 script 의 경로를 "/js/app.js" 로 설정을 하면 서버에 등록된 경로를 통해 script 를 가져옵니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Chatting</title>
</head>
<body>
<header>Chatting Web Page</header>
<main>
<h2>Welcome</h2>
</main>
</body>
<script type="text/javascript" src="/js/app.js"></script>
</html>
실행
localhost:3000 에 재접속하면 script 의 alert 명령어가 실행되는것을 확인할 수 있습니다.
'Javascript' 카테고리의 다른 글
chatting server - 채팅방 생성 및 접속(3) (0) | 2023.02.25 |
---|---|
chatting server - 채팅방 생성 및 접속(2) (0) | 2023.02.25 |
chatting server - 채팅방 생성 및 접속(1) (0) | 2023.02.24 |
chatting server - socket.io 연결 (0) | 2023.02.24 |
chatting server - 환경설정 (0) | 2023.02.24 |