주특기 과제는 게시판과 해당 게시판에 등록되어 있는 댓글을 구현하는 과제이다.
따라서 index.js에서 Router를 두 개로 두어 진행하였다.
//index.js
//posts router 연결
router.use('/posts', postrouter);
// comments router 연결
// 왜 이렇게 하면 안되는 지는 모르겠지만, 이렇게 하면 :postid를 req.params로 받아오지 못한다.
// router.use('/posts/:postid/comments', commentrouter)
// comments.js
// 댓글 생성하기
router.post('/', async (req, res) => {
try {
await Comments.create({
post_id: req.params.postid,
user_id: req.body.user_id,
user_password: req.body.user_password,
comment_content: req.body.comment_content,
});
res.status(201).json({ message: '댓글을 생성하였습니다.' });
} catch (err) {
if (!req.body.comment_content) {
res.status(400).json({ message: '댓글 내용을 입력해주세요.' });
} else {
res.status(400).json({ message: '데이터 형식이 올바르지 않습니다.' });
}
}
});
주석에도 달려있지만, index.js를 저렇게 작성할 경우, postid를 req.params로 받아오지 못했다.
//posts router 연결 후 commentrouter 연결
router.use('/posts', postrouter, commentrouter);
router.get('/:postid/comments', async (req, res) => {
try {
// 이하 생략
router.use 안에 postrouter, commentrouter를 동시에 넣어줬다.