728x90
반응형
이제, 게시글을 수정하거나 삭제하는 기능이 필요하다.
백엔드에서 해야 할 작업은 게시판 관련 컨트롤러에 기능을 추가하고 라우터만 추가하면 된다.
| 게시글 수정/삭제 기능 추가
backend/controllers/postController.js
// 글 수정
exports.updatePost = async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (!post) return res.status(404).json({ message: '게시글 없음' });
if (post.author.toString() !== req.user.id)
return res.status(403).json({ message: '권한 없음' });
post.title = req.body.title || post.title;
post.content = req.body.content || post.content;
const updated = await post.save();
res.json(updated);
} catch (error) {
res.status(500).json({ message: '게시글 수정 오류', error: error.message });
}
};
// 글 삭제
exports.deletePost = async (req, res) => {
try {
const post = await Post.findById(req.params.id);
if (!post) return res.status(404).json({ message: '게시글 없음' });
if (post.author.toString() !== req.user.id)
return res.status(403).json({ message: '권한 없음' });
await post.deleteOne();
res.json({ message: '삭제 완료' });
} catch (error) {
res.status(500).json({ message: '게시글 삭제 오류', error: error.message });
}
};
| 라우터 추가
backend/routes/postRoutes.js
router.put('/:id', protect, postController.updatePost); // 수정
router.delete('/:id', protect, postController.deletePost); // 삭제
백엔드에는 추가만 하면 되고 이제 프론트엔드에서 실제로 보여지고 동작이 가능하도록 해야 한다.
다음 작업에서 시작한다.
728x90
반응형
'STUDY > Project' 카테고리의 다른 글
마무리 작업 - HomePage, 이동버튼 추가 (0) | 2025.05.08 |
---|---|
게시글 수정 페이지 작성 및 삭제 추가 - EditpostPage, PostDetailPage (0) | 2025.05.07 |
프론트엔드 기능별 라우터 분리 - routes/ (0) | 2025.05.06 |
게시판 페이지 작성 - PostListPage, PostDetailPage, CreatePostPage (0) | 2025.05.06 |
전역 상태 관리하기 - AuthContext, 로그아웃 기능 (0) | 2025.05.05 |