728x90
노마드 코더의 줌 클린코딩을 공부한 내용입니다.
채팅 서버를 만들기 위한 express 서버를 구축한다.
폴더 구조
📁 chat
┣ 📁 src
┃ ┣ 📁 public
┃ ┃ ┗ 📁 js
┃ ┃ ┃ ┗ 📄 app.js
┃ ┗ 📁 views
┃ ┃ ┗ 🐶 home.pug
┃ ┗ 📄 server.js
프론트엔드
home.pug
에 웹 페이지를 구성한다.
MVP.css 라는 css 프레임워크를 이용하기 위해 link 해준다.
link(rel="stylesheet", href="https://unpkg.com/mvp.css")
본문 내용을 작성한다.
body
header
h1 Chat
main
h2 hello
스크립트는 app.js를 사용할 것이기 때문에 이를 명시해준다.
script(src="/public/js/app.js")
app.js
에 스크립트 내용을 작성한다.
간단히 웹에 접속하면 'hi' 팝업을 띄우도록 한다.
alert("hi")
백엔드
server.js
에 웹 서버를 구성한다.
여기서는 express로 웹 서버를 구성한다.
먼저 express 라이브러리를 임포트한다.
const express = require('express');
express로 웹 서버를 구성하고, 포트를 지정하여 열어준다.
const app = express();
const PORT = 3000;
const handleListen = () => console.log(`Listening on http://localhost:${PORT}`);
app.listen(PORT, handleListen);
사용할 view engine 과 views 를 지정해준다.
app.set("view engine", "pug");
app.set("views", __dirname + "/views");
라우팅을 해준다.
localhost의 3000번 포트에 연결하면 home.pug를 보여준다.
app.use("/public", express.static(__dirname + "/public"));
app.get("/", (req, res) => res.render("home"));
전체코드
home.pug
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 Chat
link(rel="stylesheet", href="https://unpkg.com/mvp.css")
body
header
h1 Chat
main
h2 hello
script(src="/public/js/app.js")
app.js
alert("hi")
server.js
const express = require('express');
const app = express();
const PORT = 3000;
app.set("view engine", "pug");
app.set("views", __dirname + "/views");
app.use("/public", express.static(__dirname + "/public"));
app.get("/", (req, res) => res.render("home"));
const handleListen = () => console.log(`Listening on http://localhost:${PORT}`);
app.listen(PORT, handleListen);
728x90
'Web > Node.js' 카테고리의 다른 글
[Nodejs] express 템플릿으로 html 사용하기 (0) | 2022.04.22 |
---|---|
[NodeJS] Google 로그인 API 구현하기 (0) | 2022.03.25 |
[NodeJS] WebSocket을 이용한 채팅 (0) | 2022.02.24 |
[NodeJS] Nodemon, Babel (0) | 2022.02.18 |