oris9
간단한 Express 실습 본문
데이터파일
data.json
더보기
{
"soccer": {
"name": "Soccer",
"subscribers": 800000,
"description": "The football subreddit. News, results and discussion about the beautiful game.",
"posts": [
{
"title": "Marten de Roon to make pizza for more than 1,000 people in Bergamo if Atalanta win the Champions league.",
"author": "joeextreme"
},
{
"title": "Stephan Lichtsteiner has retired from professional football",
"author": "odd person"
},
{
"title": "OFFICIAL: Dani Parejo signs for Villareal.",
"author": "joeextreme"
}
]
},
"chickens": {
"name": "Chickens",
"subscribers": 23956,
"description": "A place to post your photos, video and questions about chickens!",
"posts": [
{
"title": "Naughty chicken hid under a shed for 3 weeks and came home with 25 chicks today!",
"author": "joeextreme",
"img": "https://preview.redd.it/pcn8u4j7c9z61.jpg?width=960&crop=smart&auto=webp&s=e114976dde1108b9556555d2db36a3cb6211798d"
},
{
"title": "Had to kill my first chicken today. Does it get any easier?",
"author": "sad boi"
},
{
"title": "My five year old chicken set and hatched one baby. I guess she wanted to be a mama one more time.",
"author": "tammythetiger",
"img": "https://preview.redd.it/lervkuis3me51.jpg?width=640&crop=smart&auto=webp&s=6a18ab3c4daa80eccf3449217589b922fa443946"
}
]
},
"mightyharvest": {
"name": "Mighty Harvest",
"subscribers": 44002,
"description": "Feeding many villages and village idiots for 10s of days.",
"posts": [
{
"title": "My first meyer lemon ripened today. Im so proud of the little guy. Banana for scale",
"author": "proudmamma",
"img": "https://preview.redd.it/1bz6we4j54941.jpg?width=640&crop=smart&auto=webp&s=a036ea99299f7737efde9f6c3bfa43893f5eaa00"
},
{
"title": "I think I overestimated the harvest basket size I needed.",
"author": "grower123",
"img": "https://preview.redd.it/4h99osd25i351.jpg?width=640&crop=smart&auto=webp&s=d651250a345bbceeba7a66632e8c52a02d71bc73"
}
]
}
}
index.js
// express.static(root,[options])
// app.use(express.static('public')); // 괄호안에 있는것; 미들웨어 - 요청이 들어오면 응답을 내보내는 식으로 작동함
const express = require("express");
const app = express();
const path = require("path"); // (1) index.js가 있는 디렉토리안의 views디렉토리를 찾음
const redditData = require("./data.json"); // data
app.use(express.static(path.join(__dirname, "public"))); // css stylesheet 절대경로로 수정
//익스프레스는 뷰나 템플릿이 views디렉토리 안에있다고 생각함
//(디폴트, 바꿀수있음 - app.set('views')이용 - 홈페이지 참고)
/**app.set(설정하려는 키/특성, 해당 값) */
app.set("view engine", "ejs"); // 따로 불러오기 할 필요없이, app.set으로 불러옴
app.set("views", path.join(__dirname, "/views")); // (2) index.js가 있는 디렉토리안의 views디렉토리를 찾음
app.get("/", (req, res) => {
res.render("home");
/**res.render(view [,locals][,callback]) ; view를 렌더링하고 렌더링된 html문자열을 클라이언트에 보냄 */
});
app.get("/cats", (req, res) => {
const cats = ["Rus", "cute", "love", "oris"];
res.render("cats", { cats });
});
app.get("/r/:subreddit", (req, res) => {
const { subreddit } = req.params;
const data = redditData[subreddit]; // data
if (data) {
res.render("subreddit", { ...data });
} else {
res.render("notfound", { subreddit });
}
});
app.get("/rand", (req, res) => {
const num = Math.floor(Math.random() * 10) + 1;
res.render("random", { num: num });
});
app.listen(3000, () => {
console.log("Example app listening on port 3000!");
});
아래부터 views 디렉토리
cats.ejs
<!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>I LOVE CATS</h1>
<ul>
<% for(let cat of cats) {%>
<li><%=cat%></li>
<% } %>
</ul>
</body>
</html>
home.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Home</title>
</head>
<body>
<h1>homepage</h1>
<%= 3+2+3 %>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Placeat
laudantium praesentium tempore saepe ab cupiditate, libero, reprehenderit,
vel cumque et corporis animi! Numquam, pariatur ab aspernatur quaerat
eveniet corrupti cupiditate!
</p>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Placeat
laudantium praesentium tempore saepe ab cupiditate, libero, reprehenderit,
vel cumque et corporis animi! Numquam, pariatur ab aspernatur quaerat
eveniet corrupti cupiditate!
</p>
</body>
</html>
random.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Random</title>
</head>
<body>
<h1>Random : <%=num%></h1>
<% if(num%2 ===0) { %>
<h2>that is even number</h2>
<% } else {%>
<h2>that is odd number</h2>
<% } %>
<h3><%= num%2 === 0 ? 'EVEN' : 'ODD' %></h3>
</body>
</html>
subreddit.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title><%= name %> </title>
<link rel="stylesheet" href="/app.css">
</head>
<body>
<h1>Browsing The <%= name %> subreddit</h1>
<h2><%= description %></h2>
<p><%=subscribers %> Total Subscribers</p>
<hr>
<% for(let post of posts) { %>
<article>
<p><%= post.title %> - <b><%=post.author %></b></p>
<% if(post.img) { %>
<img src="<%= post.img %>" alt="">
<% } %>
</article>
<% } %>
</body>
</html>
public 폴더안에 app.css 존재
'Node.js' 카테고리의 다른 글
[Node.js] 미들웨어에 대해 알아보기 (0) | 2024.03.02 |
---|---|
[Node.js] Node.js 란? (0) | 2024.03.01 |
Express 라우터, 쿠키, 세션 플래시 (0) | 2024.02.20 |
Mongoose express (0) | 2024.02.17 |
[Node] npm (0) | 2024.02.04 |