Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial![](https://ecs-static.teamtreehouse.com/assets/views/marketing/shared/community-banner-white-47072046c51352fe6a69f5e691ff5700b28bb11d45197d7bdf066d9ea3f72d0c.webp)
![benjaminfarnham](https://uploads.teamtreehouse.com/production/profile-photos/9728912/micro_ben-profile.jpg)
benjaminfarnham
8,055 PointsNot getting 404 error when I use a route with an ID that doesn't exist.
So maybe I am just trying to be overly thorough here but I was able to follow the instructions and honestly understand what was being presented but my variable routes (/:id) don't give a 404 error when given a route that doesn't exist (i.e. /cards/8).
My console is logging an error (RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: undefined) but I really want to make sure the application is rock solid so I can move forward with best practices.
Am I missing something?
app.js
const express = require("express");
const bodyParser = require("body-parser"); // Middleware that parses form data
const cookieParser = require("cookie-parser"); // Middleware that parses cookie data
const app = express();
app.use(bodyParser.urlencoded({extended: false}));
app.use(cookieParser());
const mainRoutes = require('./routes/index.js');
const cardRoutes = require('./routes/cards.js');
app.use(mainRoutes);
app.use('/cards',cardRoutes);
app.set("view engine", "pug");
// 404 message
app.use((req, res, next) => {
const err = new Error(`Not found`);
err.status = 404;
next(err);
});
// Error handler
app.use((err, req, res, next) => {
res.locals.error = err;
res.status(err.status);
res.render('error', err);
});
app.listen(1337, () => {
console.log("The app is running on 'localhost:1337'");
});
cards.js (with route in question that doesn't give the 404)
const express = require("express");
const router = express.Router();
const { data } = require('../data/flashcardData.json');
const { cards } = data;
router.get("/:id", (req, res) => {
res.render("card", {
the requests params key. (req.params.varName)
prompt: cards[req.params.id].question,
hint: cards[req.params.id].hint
});
});
module.exports = router;
2 Answers
![Greg Kaleka](https://secure.gravatar.com/avatar/54c2cac346df05d7b70cc0a6825c1cba?s=96&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
Greg Kaleka
39,021 PointsHey Benjamin,
Great question. You're not doing anything wrong.
Let's think about what's happening:
- User goes to /cards/9999
- Express looks for a route that matches that pattern
- Express find /cards/:id, which matches perfectly, so no 404 - it calls
get("/:id")
- Inside of
get("/:id")
, your code looks forcards[9999].question
What happens on step 4? TypeError: cards[9999] is undefined
. And that error has a status of undefined
. So, back in app.js
, you have an error handler that returns the err.status as the res.status, and undefined
is not a valid HTTP response status!
How can we handle this? Add error handling to your cards.js
code. This may be a bit beyond what you've seen before, so don't worry if it isn't familiar. you don't necessarily need to learn this now, but this is the basic idea.
We can wrap our card lookup in a try-catch block. That would look something like this (important note - I know nothing about express.js, so it is very likely this will not actually work. Hopefully it gives you the general idea, though):
const express = require("express");
const router = express.Router();
const { data } = require('../data/flashcardData.json');
const { cards } = data;
router.get("/:id", (req, res) => {
res.render("card", {
try {
card = cards[req.params.id];
}
catch(err) {
if err.status === "undefined" {
req.status = 404;
}
}
prompt: card.question,
hint: card.hint
});
});
module.exports = router;
Hope that's helpful! Let me know if you have any conceptual questions about this. Again, I'm not at all sure this will actually work, but it's the right idea of how to approach it.
Edit:
OK, I couldn't help myself, so I figured it out. What I was doing was pretty substantially wrong hah. This version works:
const express = require('express');
const router = express.Router();
const { data } = require('../data/flashcardData.json');
const { cards } = data;
router.get('/:id', (req, res) => {
try {
selected_card = cards[req.params.id];
if (selected_card === undefined) {
throw 404;
}
res.render('card', {
prompt: selected_card.question,
hint: selected_card.hint
});
}
catch(err) {
console.log('caught error ' + err);
if (err === 404) {
res.sendStatus(404);
}
}
});
module.exports = router;
![Courtney Wilson](https://secure.gravatar.com/avatar/a3f49ae64315d3c7e738aabe9d05defc?s=96&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
Courtney Wilson
8,031 PointsFor anyone else wondering the same, another way to do what Greg is doing is to use an if/else statement and if the array index doesn't exist, redirect to '/not-found' so that the 404 middleware function will pick it up:
router.get('/:id', (req, res) => {
if (req.params.id) {
res.render('card', {
prompt: cards[req.params.id].question,
hint: cards[req.params.id].hint
});
} else {
res.redirect('/not-found');
}
});
![JASON LEE](https://secure.gravatar.com/avatar/798eb96d4c2cc69af1ecaf0ccb0b8be5?s=60&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
JASON LEE
17,352 Pointsrouter.get('/:id', (req, res) => {
if (req.params.id) { // this line item
res.render('card', {
prompt: cards[req.params.id].question,
hint: cards[req.params.id].hint
});
} else {
res.redirect('/not-found');
}
});
Should be
router.get('/:id', (req, res) => {
if (cards[req.params.id]) { // should be this line item
res.render('card', {
prompt: cards[req.params.id].question,
hint: cards[req.params.id].hint
});
} else {
res.redirect('/not-found');
}
});
benjaminfarnham
8,055 Pointsbenjaminfarnham
8,055 PointsI ended up testing the try catch block and was able to get some success. Still some kinks to work out though. Thanks for responding! As crazy as it may be, I am just determined to get the best practices down as fast as possible. ;)
Greg Kaleka
39,021 PointsGreg Kaleka
39,021 PointsThat's awesome - totally understand that attitude, and it will take you far!
Check out my edit above; I got it working.