Notice
Recent Posts
Recent Comments
«   2024/12   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31
Archives
Today
Total
관리 메뉴

SYDev

[Express] 15. Delete Comment POST 본문

대딩코딩/웹개발 스터디

[Express] 15. Delete Comment POST

시데브 2023. 12. 1. 21:03

Post 방식으로 Delete Comment

 파일명: commentRouter.js

const express = require('express');
const router = express.Router();
const commentController = require('../controllers/commentController.js');

router.post('/create/:topic_id', commentController.createComment);
router.post('/delete/:comment_id', commentController.deleteComment);    //댓글 삭제


module.exports = router;

 

 

 파일명: commentController.js

const commentModel = require('../models/commentModel.js');

module.exports = {
    createComment: async (req, res) => {
        const topicId = req.params.topic_id;
        const newCommentData = req.body;
        await commentModel.createComment(topicId, newCommentData);

        res.redirect(`/topic/read/${topicId}`);
    },
    deleteComment: async (req, res) => {
        const commentId = req.params.comment_id;    

        const comment = await commentModel.getComment(commentId);   //댓글 가져오기
        await commentModel.deleteComment(commentId);    //댓글 삭제

        res.redirect(`/topic/read/${comment.topic_id}`);
    }
}

 

 

 파일명: commentModel.js

const db = require('../config/db.js');

module.exports = {
    createComment: async (topicId, newCommentData) => {
        const query = 'INSERT INTO Comments(username, content, topic_id) VALUES(?, ?, ?);';
        await db.query(query, [newCommentData.username, newCommentData.content, topicId]);
    },
    getComments: async (topicId) => {
        const query = 'SELECT * FROM Comments WHERE topic_id=?;';
        const comments = await db.query(query, [topicId]);

        return comments[0];
    },
    deleteComment: async (commentId) => {
        const query = 'DELETE FROM Comments WHERE comment_id=?;';
        await db.query(query, [commentId]);
    },
    getComment: async (commentId) => {
        const query = 'SELECT * FROM Comments WHERE comment_id=?;';
        const comment = await db.query(query, [commentId]);

        return comment[0][0];
    }
}

 

 

>> 정상적으로 삭제됨

'대딩코딩 > 웹개발 스터디' 카테고리의 다른 글

[Express] 17. Display Comment Fetch  (0) 2023.12.04
[Express] 16. Create Comment Fetch  (0) 2023.12.04
[Express] 14. Create Comment POST  (0) 2023.12.01
[Express] 13. Routing  (0) 2023.12.01
[Express] 12. Update Topic POST  (0) 2023.12.01