백엔드/Node.js
EJS
Ryuzy
2025. 4. 22. 01:40
728x90
반응형
1. EJS
EJS(Embedded JavaScript)는 HTML 안에 <%= %>, <% %> 문법을 이용해 JavaScript 코드를 삽입할 수 있도록 도와주는 템플릿 엔진입니다. 서버에서 데이터를 넘겨주면, 그 데이터를 HTML에 자동으로 넣어서 브라우저에 보낼 수 있게 해줍니다.
1. 설치
npm install ejs
2. 📁 프로젝트 구조
ejs-test/
├── views/
│ └── index.ejs
├── server.js
├── package.json
view/index.ejs
<!DOCTYPE html>
<html>
<head>
<title>EJS HTTP 예제</title>
</head>
<body>
<h1>안녕하세요, <%= name %>님!</h1>
</body>
</html>
server.js
const http = require("http");
const fs = require("fs");
const ejs = require("ejs");
const path = require("path");
const server = http.createServer((req, res) => {
if (req.url === "/") {
// 템플릿 파일 경로
const filePath = path.join(__dirname, "views", "index.ejs");
// EJS 렌더링
ejs.renderFile(filePath, { name: "김사과" }, (err, data) => {
if (err) {
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("서버 오류");
return;
}
res.writeHead(200, { "Content-Type": "text/html" });
res.end(data);
});
} else {
res.writeHead(404, { "Content-Type": "text/plain" });
res.end("페이지를 찾을 수 없습니다.");
}
});
server.listen(3000, () => {
console.log("서버 실행 중 → http://localhost:3000");
});
3. 사용자 리스트 출력
📄 views/users.ejs
<!DOCTYPE html>
<html>
<head><title>사용자 목록</title></head>
<body>
<h2>사용자 목록</h2>
<ul>
<% users.forEach(function(user) { %>
<li><%= user %></li>
<% }); %>
</ul>
</body>
</html>
📄 server.js (추가)
else if (req.url === "/users") {
const filePath = path.join(__dirname, "views", "users.ejs");
const users = ["김사과", "반하나", "오렌지"];
ejs.renderFile(filePath, { users }, (err, data) => {
if (err) {
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("렌더링 오류");
return;
}
res.writeHead(200, { "Content-Type": "text/html" });
res.end(data);
});
}
4. 게시글 출력
📄 views/posts.ejs
<!DOCTYPE html>
<html>
<head><title>게시판</title></head>
<body>
<h1>게시글 목록</h1>
<% posts.forEach(post => { %>
<div>
<h3><%= post.title %></h3>
<p><%= post.content %></p>
<hr />
</div>
<% }); %>
</body>
</html>
📄 server.js (추가)
else if (req.url === "/posts") {
const filePath = path.join(__dirname, "views", "posts.ejs");
const posts = [
{ title: "첫 글", content: "안녕하세요!" },
{ title: "둘째 글", content: "Node.js 재미있어요!" }
];
ejs.renderFile(filePath, { posts }, (err, data) => {
if (err) {
res.writeHead(500, { "Content-Type": "text/plain" });
res.end("렌더링 오류");
return;
}
res.writeHead(200, { "Content-Type": "text/html" });
res.end(data);
});
}
728x90
반응형