node.js - 在 Node 中发出 DELETE 请求时如何修复 [ERR_HTTP_HEADERS_SENT]

标签 node.js express mongoose

我有一个帖子路由,人们可以在其中向帖子添加评论。我添加了以帖子的唯一 ID 为目标的功能来删除它。该帖子被删除,但有些东西再次被调用,我相信当它检查时,该帖子不再存在并返回错误。我的代码中的哪里可以调用两次?

然后我检查它是否在数据库中被删除,并且已经被删除了。

我正在学习 Mongoose 和路由,但逻辑看起来不错?但如果我遗漏了什么,请纠正我。

我正在使用 Postman 来测试后端逻辑。尝试了两个不同的用户,但结果是一样的。

我的代码:

// @route   DELETE api/posts/:ID
// @desc    Delete post
// @access  private
router.delete("/:id", passport.authenticate("jwt", {session: false}), (req, res) => {
    Profile.findOne({user: req.user.id})
        .then(profile => {
            Post.findById(req.params.id)
                .then(post => {
                    //Check for post owner
                    if(post.user.toString() !== req.user.id){
                            return res.status(401).json({notauthorised: "User not authorised"});
                    }                       
                    // Delete
                    post.remove().then(() => {
                        console.log("Success 1")
                        return res.json({success: true})

                    });      
                })
                .catch(err = res.status(404).json({postnotfound: "No post found"}))
        })
})

控制台错误消息:

Success 1
(node:5228) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:470:11)
    at ServerResponse.header (D:\Google Drive\Test Lab\Projects\mernTutorial\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (D:\Google Drive\Test Lab\Projects\mernTutorial\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (D:\Google Drive\Test Lab\Projects\mernTutorial\node_modules\express\lib\response.js:267:15)
    at post.remove.then (D:\Google Drive\Test Lab\Projects\mernTutorial\routes\api\posts.js:83:36)
    at process._tickCallback (internal/process/next_tick.js:68:7)
(node:5228) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with
.catch(). (rejection id: 1)
(node:5228) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

这就是让我认为某件事被调用两次的原因,因为 Success 1 消息出现在最后,然后是错误。

我希望当帖子被删除时,它会用 json 字符串响应用户,{success: true} 但我在 postman 中收到 {postnotfound: "No post found"}

最佳答案

我能看到的唯一明显的可能是您错误的根本原因是,

   .catch(err = res.status(404).json({postnotfound: "No post found"}))

您试图在 catch block 的参数内声明一个变量,我认为这是不正确的,但是,您可以在 catch 参数内有一个箭头函数,我相信这就是这段代码中的 catch。

关于node.js - 在 Node 中发出 DELETE 请求时如何修复 [ERR_HTTP_HEADERS_SENT],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57163400/

相关文章:

node.js - 找不到模块 'node_modules/formidable'

javascript - javascript中的链式 promise

mongodb - 使用 mongoose 更新许多 - 更新对象数组

node.js - Mongoose db find方法之前的 Node 功能整理

node.js - Google 上的 Actions AskForNewSurface 未切换

node.js - 如何让 VSCode 附加到 NPM 启动的 nodemon 上?

mysql - 为什么我的 React 应用程序(具有 Node 和 mysql 后端)可以在本地运行,但不能在 Heroku 上运行?

mysql - TypeError : app. post(...).then 不是一个函数

mongodb - 如何检查数据库(mongodb)中是否存在用户名和密码

javascript - async.waterfall 失去了范围