我正在学习使用nodejs,express,mongoose,handbars制作一个网站。删除网页上评论的回复时遇到问题

问题描述 投票:0回答:1

我正在学习创建一个网站,允许用户发布博客、评论博客并回复这些评论。我在评论模式中使用了replies[this]来处理对评论的回复。但我无法允许用户删除这些回复。这是我的服务器端代码,用于删除评论和回复:

// Delete a specific comment or reply
app.get('/deleteComment/:postId/:commentId', requireLogin, async (req, res) => {
    try {
        const currentUser = req.user; 
        const { replyId } = req.query; 
        const foundPost = await Post.findById(req.params.postId);
        
        if (replyId) {  // If it's a reply
            const comment = foundPost.comments.id(req.params.commentId);
            const reply = comment.replies.id(replyId);
            
            // Check if the user is the author of the reply
            if (reply.commentUser.toString() !== currentUser._id.toString()) {
                return res.status(403).send('Permission denied: You can only delete your own replies.');
            }

            reply.remove();
        } else {  // It's a top-level comment
            const comment = foundPost.comments.id(req.params.commentId);

            // Check if the user is the author of the comment
            if (comment.commentUser.toString() !== req.user._id.toString()) {
                return res.status(403).send('Permission denied: You can only delete your own comments.');
            }

        
            comment.remove();
        }
        
        await foundPost.save();
        res.status(200).send('Deleted successfully');
    } catch (err) {
        console.log(err);
        res.status(500).send("An error occurred");
    }
});

这是我的前端,

  <a href="#" onclick="deleteComment('{{../post._id}}', '{{_id}}')">
            <i class="fa fa-trash post-icons"></i>
          </a>
  function deleteComment(postId, commentId) {
    const xhr = new XMLHttpRequest();
    xhr.open('GET', `/deleteComment/${postId}/${commentId}`, true);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                location.reload(); 
            } else if (xhr.status === 403) {
               
                alert('Permission denied: You can only delete your own comments.');
            } else {
               
                alert('An error occurred while deleting the comment.');
            }
        }
    };
    xhr.send();
}

回复作为对象存储在猫鼬注释数组内的数组中 评论:数组 0:对象 评论用户对象 ID:650 评论正文:“你好世界” 创建日期:2023 回复: 数组 0:对象 评论用户:对象 commentBody:“你好世界回复” 创建日期:2023

每次我尝试删除回复时,都会收到 404 错误。我可以删除评论,只是回复。我尝试了很多方法,例如更改路由和函数以包含replyId,但它只是不断给出 404 错误。有什么想法为什么不起作用吗?

javascript node.js express mongoose handlebars.js
1个回答
0
投票

以下是我可以从您提供的代码片段中告诉您的内容:

在此路由中删除评论是有效的,因为

/deleteComment/:postId/:commentId
接收
postId
commentId
,这是删除评论所需的唯一两个参数。当您尝试删除回复时,您的服务器端代码不会收到所需的
replyId

有多种方法可以解决这个问题。我建议你将请求从 GET 更改为 POST 即可。

服务器端:

app.post('/deleteComment', requireLogin, async (req, res) => {
    try {
        const currentUser = req.user; 
        // Extract from the request body
        const { postId, commentId, replyId } = req.body;  
        
        const foundPost = await Post.findById(postId);

        // If it's a reply
        if (replyId) {  
            const comment = foundPost.comments.id(commentId);
            const reply = comment.replies.id(replyId);
            
            // Check if the user is the author of the reply
            if (reply.commentUser.toString() !== currentUser._id.toString()) {
                return res.status(403).send('Permission denied: You can only delete your own replies.');
            }

            reply.remove();
        } else { 
            // It's a top-level comment
            const comment = foundPost.comments.id(commentId);

            // Check if the user is the author of the comment
            if (comment.commentUser.toString() !== req.user._id.toString()) {
                return res.status(403).send('Permission denied: You can only delete your own comments.');
            }

            comment.remove();
        }
        
        await foundPost.save();
        res.status(200).send('Deleted successfully');
    } catch (err) {
        console.log(err);
        res.status(500).send("An error occurred");
    }
});

前端:

function deleteComment(postId, commentId, replyId) {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', '/deleteComment', true);
    xhr.setRequestHeader('Content-Type', 'application/json;charset=UTF-8');
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                location.reload();
            } else if (xhr.status === 403) {
                alert('Permission denied: You can only delete your own comments.');
            } else {
                alert('An error occurred while deleting the comment.');
            }
        }
    };
    xhr.send(JSON.stringify({
        postId: postId,
        commentId: commentId,
        replyId: replyId
    }));
}

现在确保您使用两个不同的锚点,一个用于删除回复,一个用于删除帖子:

删除评论:

 <a href="#" onclick="deleteComment('{{../post._id}}', '{{_id}}')">
     <i class="fa fa-trash post-icons"></i>
 </a>

删除回复(确保为replyId使用正确的变量)

 <a href="#" onclick="deleteComment('{{../post._id}}', '{{_id}}', '{{replyId}}')">
     <i class="fa fa-trash post-icons"></i>
 </a>

您可以采取的另一种方法是创建两个单独的 GET 路由。一个处理删除回复,另一个处理删除评论。

当您使用路由删除某些内容时,使用 DELETE 路由也是一个很好的做法。

如果您需要更多帮助,我很乐意提供帮助:)

© www.soinside.com 2019 - 2024. All rights reserved.