得到 "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" 即使我只有一个 res.render()

Getting "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client" even though I only have one res.render()

我正在使用 Mongoose 和 Express/Node.js 构建一个简单的 api,但是当我尝试单击“阅读更多”link(它使用 Express 路由参数),我收到“错误 [ERR_HTTP_HEADERS_SENT]:将它们发送到客户端后无法设置 headers”。我知道当针对单个 post 发送多个响应时会发生这种情况,但我一辈子都找不到发生这种情况的地方。

我的代码如下:

  Post.find({}, function(err, foundPosts) {
    res.render("home", {homeStartingContent: homeStartingContent, posts: foundPosts});
    res.redirect("/");
  });


})

app.get("/compose", function(req, res) {
  res.render("compose");
})

app.post("/compose", function(req, res) {
  const post = new Post({
    title: req.body.title,
    body: req.body.newPost,
    teaser: req.body.newPost.substring(0,99) + "...",
  });

  // save the post and refresh home page to display most recent post
  post.save(function(err) {
    if(!err) {
      res.redirect("/");
    }
  });
});

// express routing parameters; uses whatever comes after : to decide what to do
app.get("/posts/:postId", function(req, res) {
  const requested = _.lowerCase(req.params.postId);
  Posts.findOne({_id: requested}, function(err, post) {
    res.render("post", {post: post});
  });
});```

I'm pretty sure the issue is in the last app.get("/posts/:postID"...), but I can't figure it out.

I understand that this happens when multiple responses are sent for a single post

如果您在发送回复后发送更多 headers,也会发生这种情况。这就是您通过先调用 res.render 然后调用代码片段顶部附近的 res.redirect 来实现的。此外,这没有意义,因为 redirection 会阻止用户阅读您之前 render 编辑的内容。