Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript Express Basics Parameters, Query Strings, and Modularizing Routes Linking Around the Application

Jef Davis
Jef Davis
29,162 Points

Redirect to 404 for non-existent card

I'm noticing that while the app will render the 404 error page if I try to navigate to:

localhost:3000/doesnotexist

But if I try to navigate to

localhost:3000/cards/7

the app does not redirect to the 404 page.

My thoughts are that this is the case because the /cards/ portion of the URL is defined in the app's routes, but how could I add some middleware in the cards route to return a 404 error if a non-existent card, (e.g. #7) were entered?

3 Answers

Jef Davis
Jef Davis
29,162 Points

Oh, I figured it out. I basically answered my own question above: Because the /cards route is defined in the app, the route doesn't really care what int value for id the user enters.

I added this to the get('/:id') in cards:

    if (id > cards.length) {
        return res.redirect('/404');
    }

Also, because Andrew noted that the query string allowed users to view an incorrect page when navigating to "?side=hint", I added an the following else clause to the if/else if for question and answer query strings:

else {
        return res.redirect('/404'); 
    }

This redirect ensures that only the query string "side=question" or side=answer" will display.

Vitaly Khe
Vitaly Khe
7,160 Points

Jef, just one moment in your code: the condition when id = cards.length is not working too, because we have cards.length = 5, and you accessing them from 0 to 4.

So, this should work

 if (id >= cards.length) {
        return res.redirect('/404');
    }
Vitaly Khe
Vitaly Khe
7,160 Points

BTW, in my code your solution doesn't work. if i set redirect for this case, I'm getting error that very well desciribed here: https://stackoverflow.com/questions/7042340/error-cant-set-headers-after-they-are-sent-to-the-client

Pls chek how i workarounded this:

app.js

app.use((err, req, res, next) => {
  res.locals.error = err;
  if(err.status) {
    res.status(err.status);
    console.log('Error status code is: ', err.status);
  } else {
    res.status(404);
    console.log('Error status code is undefined. Setting response status to 404. Error status: ', err.status);
  }
  res.render('error');
});