Colton Van Bastelaere
Colton Van Bastelaere

Reputation: 355

How to redirect after an error in Express

I am using Express for routing and MongoDB for my simple Node blog app (I'm new and just learning) and I need to redirect to the home page if somebody enters the incorrect URL, whenever it attempts to redirect the program crashes.

Terminal Output:

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

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

Router Params / Get

//=== 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`);
        } */
    });
});

The program will only crash if I type in an incorrect URL, after that, none of my pages will reload (I'm assuming because of the (err) callback), I have to restart my server manually and everything works again, nodemon doesn't reset it when it fails.

root view:

<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>
<% }) %>

Upvotes: 0

Views: 747

Answers (1)

Jamal Abo
Jamal Abo

Reputation: 472

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(`/`);
    });
});

the code didn't work before (maybe) because you are checking if there an error and if not rendering post but this does not mean that the post was found, you need to check if foundPost is not null.

Upvotes: 1

Related Questions