프로그래밍 언어/Node.js
[RESTful 라우트] RESTful 주석 Index 구현하기
jjinny_0609
2023. 11. 13. 21:59
728x90
이번 글에서는 Express를 사용하여 댓글 리소스의 RESTful 라우트를 구현하는 방법에 대해 알아보겠습니다. RESTful 방식으로 앱을 구조화하는 다양한 방법이 있지만, 이번에는 주어진 앱에서 EJS를 활용하여 HTML을 제공하는 RESTful 앱을 만들어보겠습니다. 사용자가 양식과 상호작용하여 새 댓글을 작성하거나 기존 댓글을 편집할 수 있는 기능을 구현할 것입니다.
EJS 설정
먼저, EJS를 설치하고 설정합니다.
npm i ejs
app.js 작성
// app.js
const express = require('express');
const app = express();
const path = require('path');
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
댓글 목록 렌더링
댓글 목록을 렌더링하는 첫 번째 라우트를 만들어봅시다.
// app.js
const comments = [
{
username: 'Todd',
comment: 'lol that is so funny!'
},
{
username: 'Skyler',
comment: 'I like to go birdwatching with my dog'
},
{
username: 'Sk8erBoi',
comment: 'Plz delete your account, Todd'
},
{
username: 'onlysayswoof',
comment: 'woof woof woof'
}
]
app.get('/comments', (req, res) => {
res.render('comments/index', { comments });
});
위 코드에서 /comments로 오는 Get 요청을 처리하고, comments/index.ejs 템플릿에 댓글 목록을 전달하여 렌더링합니다.
EJS 템플릿 구현
이제 comments/index.ejs 템플릿에서 댓글 목록을 표시하는 작업을 합니다.
<!-- comments/index.ejs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Comments Index</title>
</head>
<body>
<h1>Comments</h1>
<ul>
<% for(let c of comments) { %>
<li><%= c.comment %> - <%= c.username %></li>
<% } %>
</ul>
</body>
</html>
위의 코드에서는 EJS의 문법을 사용하여 댓글 목록을 동적으로 표시하고 있습니다.
서버 실행 후 확인
nodemon index.js
http://localhost:3000/comments 실행
이번 글에서는 Express를 사용하여 RESTful한 댓글 리소스의 Index를 구현하는 방법을 알아보았습니다. 다음 글에서는 새 댓글을 생성하는 기능을 구현해보겠습니다. Express와 EJS를 통해 간단한 HTML을 렌더링하고, 사용자와 상호작용할 수 있는 댓글 기능을 추가하는 것은 RESTful한 앱을 구현하는 중요한 부분 중 하나입니다. 계속해서 다양한 기능을 추가해보며 RESTful한 앱을 완성해 나가시기 바랍니다! 🚀
728x90