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

Jef Davis
Jef Davis
27,603 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
27,603 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,155 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,155 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');
});