include : 하나의 파일을 다른 파일에 끼워 넣는 것
<app.js> : public 파일을 정적인 파일(.css, .js, 이미지 파일 등)로 연결
※express.static() : 정적인 파일을 연결
const express = require("express");
const dbConnect = require("./config/dbConnect");
const app = express();
app.set("view engine", "ejs");
app.set("views", "./views");
dbConnect();
app.get("/", (req, res) => {
res.status(200).send("Hello Node");
});
app.use(express.static("./public")); //public 파일을 정적인 파일로 연결로
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use("/contact", require("./routes/contactRoutes"));
app.listen(3000, () => {
console.log("3000 포트에서 서버 실행 중");
});
views -> include - <_header.ejs>, <_footer.ejs> : 헤더와 푸터를 잘라 파일로 만듬
<!--_header.ejs-->
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>연락처 관리하기</title>
<link
rel="stylesheet"
href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css"
/>
<link rel="stylesheet" href="/css/style.css" />
<link
rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css"
integrity="sha512-iecdLmaskl7CVkqkXNQ/ZH/XLlvWZOJyj7Yy7tcenmpD1ypASozpmT/E0iPtmFIB46ZmdtAc9eNBvH0H/ZpiBw=="
crossorigin="anonymous"
referrerpolicy="no-referrer"
/>
</head>
<body>
<header class="border-shadow">
<div class="container">
<nav>
<a href="/"><i class="fa-solid fa-address-book"></i> My Contacts</a>
</nav>
</div>
</header>
</body>
</html>
<!--_footer.ejs-->
</body>
</html>
views - <index.ejs> : 전체 연락처 표시 화면
<%- include('./include/_header') %> <!--_header.ejs를 인클루드-->
<main id="site-main">
<div class="button-box">
<a href="#" class="btn btn-light"
><i class="fa-solid fa-user-plus"></i>연락처 추가</a
>
</div>
<table class="table">
<thead>
<tr>
<th>이름</th>
<th>메일 주소</th>
<th>전화번호</th>
<th> </th>
</tr>
</thead>
<tbody>
<% contact.forEach(contacts => { %> <!--연속되는 contact(데이터)-->
<tr>
<td><%= contacts.name %></td> <!--사용자 이름-->
<td><%= contacts.email %></td> <!--사용자 이메일-->
<td><%= contacts.phone %></td> <!--사용자 이름-->
<td>
<a href="#" class="btn update" title="수정">
<i class="fas fa-pencil-alt"></i>
</a>
<a href="#" class="btn delete" title="삭제">
<i class="fas fa-times"></i>
</a>
</td>
</tr>
<% }); %>
</tbody>
</table>
</main>
<%- include('./include/_footer') %> <!--_footer.ejs를 인클루드-->
controllers - <contactController.js> : contact 변수에 담긴 연락처 데이터를 index.ejs로 넘김
(...)
//Get all contact, /contact
const getAllContact = asynchHandler(async (req, res) => {
const contact = await Contact.find();
res.render("index", { contact: contact }); //contact 변수를 index.ejs 파일로 넘김
});
(...)
'Do it Node.js > EJS BackEnd' 카테고리의 다른 글
18. 연락처 추가, 삭제 (0) | 2024.03.16 |
---|---|
17. 연락처 추가 (0) | 2024.03.15 |
15. EJS (0) | 2024.03.13 |
14. CRUD (0) | 2024.03.12 |
13. RESTful API (0) | 2024.03.11 |