Express中发生错误后如何重定向

时间:2019-06-27 21:11:49

标签: node.js mongodb express

我正在使用Express进行路由,而将MongoDB用于我的简单Node博客应用程序(我是新手,正在学习),如果有人输入错误的URL,则每次尝试重定向程序崩溃时,我都需要重定向到主页。

终端输出:

Server started on 3000
Rendered homepage
events.js:174
      throw er; // Unhandled 'error' event
      ^

TypeError: Cannot read property 'postTitle' of null at line 115

路由器参数/获取

//=== DYNAMIC POSTS ROUTE ===//
app.get("/posts/:postId", function(req, res){
    const requestedPostTitle = req.params.postId;
    Post.findOne({postTitle: requestedPostTitle}, function(err, foundPost){
        if (!err) {
//FAILS HERE IF INCORRECT URL IS ENTERED INTO BROWSER
            const title   = foundPost.postTitle;
            const date    = foundPost.postDate;
            const content = foundPost.postBody;
            /*res.send(foundPost.postDate);*/
            res.render(`post`, {
                  title: title,
                   date: date,
                content: content
            });

        } /*else {
        res.redirect(`/`);
        console.log(`404 ${requestedPostTitle} does not exist`);
        } */
    });
});

仅当我输入不正确的URL时程序才会崩溃,此后,我的页面都不会重新加载(我假设是由于(err)回调),我必须手动重新启动服务器,并且一切都可以正常工作,nodemon发生故障时不会重置它。

根视图:

<h1>HOME</h1>
<p><%= pageStartContent %></p>
<% posts.forEach(function(post){ %>
    <div class="post-box">
        <h3><%= post.postTitle %></h3>
        <p class="date"><%= post.postDate %></p>
        <p class="post-body"><%= post.postBody.substring(0,450) + "..." %></p>
         <a href="posts/<%= post.postTitle %>">Read More</a>
    </div>
<% }) %>

1 个答案:

答案 0 :(得分:1)

app.get("/posts/:postId", function(req, res){
    const requestedPostTitle = req.params.postId;
    Post.findOne({postTitle: requestedPostTitle}, function(err, foundPost){
        if (!err && foundPost) {
//FAILS HERE IF INCORRECT URL IS ENTERED INTO BROWSER
            const title   = foundPost.postTitle;
            const date    = foundPost.postDate;
            const content = foundPost.postBody;
            /*res.send(foundPost.postDate);*/
            return res.render(`post`, {
                  title: title,
                   date: date,
                content: content
            });

        }  
        return res.redirect(`/`);
    });
});

该代码之前(也许)无法正常工作,因为您正在检查是否有错误,是否未呈现post,但这并不意味着找到了帖子,您需要检查{{1} }不是foundPost