지난 글에서 Index 를 통해 CRUD중 Read를 작성해보았다.
이번엔 New를 이용하여 새로운 post를 생성하고 해당 post를 목록에 추가해서 Create를 구현해보자. 마찬가지로resource
는comments
를 기반으로 한다.
app.get('/comments/new', (req,res) => {
res.render('comments/new')
})
<!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>New Comments</title>
</head>
<body>
<h1>Make a new comment</h1>
<form action="/comments" method="post">
<section>
<label for="username">Enter username : </label>
<input type="text" name="username" placeholder="username" id="username">
</section>
<section>
<label for="comment">Comment Text</label>
<br>
<textarea name="comment" id="comment" cols="30" rows="5"></textarea>
</section>
<button>submit</button>
</form>
</body>
</html>
먼저 새로운 Post를 입력하는 comments/new
라우터를 생성하고, 해당 템플릿을 이용해 페이지를 구성한다.
app.post('/comments', (req,res) => {
const {username, comment} = req.body;
comments.push({username, comment});
})
이후 post 요청을 통해 생성한 글을 comments 배열에 추가하는 방식으로 구현해주고
/comments 를 확인해보면 입력한 username
과 comment
가 추가된 것을 볼 수 있다.