Home > Software design >  Getting "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client&qu
Getting "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client&qu

Time:11-08

I am using Mongoose and Express/Node.js to build a simple api, but when I try to click on the "Read More" link (which uses Express routing parameters), I get "Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client". I understand that this happens when multiple responses are sent for a single post, but I can't for the life of me find where this is happening.

My code is below:

  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.

CodePudding user response:

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

It also happens when you send more headers after already having sent a response. And that's what you do by calling first res.render and then res.redirect near the top of your code snippet. Also, this does not make sense, because the redirection will prevent the user from reading what you rendered before.

  • Related