【发布时间】:2021-11-08 01:00:37
【问题描述】:
我正在使用 Mongoose 和 Express/Node.js 构建一个简单的 api,但是当我尝试单击“阅读更多”链接(使用 Express 路由参数)时,我得到“错误 [ERR_HTTP_HEADERS_SENT]:无法设置发送到客户端后的标头”。我知道当为单个帖子发送多个回复时会发生这种情况,但我终生无法找到发生这种情况的位置。
我的代码如下:
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.
【问题讨论】: