我正在使用 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.
uj5u.com熱心網友回復:
我知道當為一個帖子發送多個回復時會發生這種情況
當您在已經發送回應后發送更多標頭時,也會發生這種情況。這就是您首先呼叫res.render然后res.redirect在代碼片段頂部附近呼叫的方法。此外,這沒有意義,因為redirect離子會阻止用戶閱讀您render之前編輯過的內容。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/352391.html
