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 trialReid Young
Courses Plus Student 14,209 PointsNow what about a route without an id?
Now that the route is variable and dependent upon a user added id to the end of the URL, e.g. localhost:3000/cards/0, how can we fix the application so that it runs if there is no id appended by the user to the URL?
I've written
router.get('/:id', (req, res) => { res.render('card', { if (req.params.id = undefined){ res.redirect('/0'); } prompt: cards[req.params.id].question, hint: cards[req.params.id].hint, answer: cards[req.params.id].answer }); });
which does not work. Now I'm confused. Thanks in advance for the help!
3 Answers
Tom Geraghty
24,174 PointsYou could do this a few ways. I think the if statement works fine. My take was to just add a second route below the specific one where an ID is provided like this:
router.get('/:id', (req, res) => {
res.render('card', {
cardFront: cards[req.params.id].question,
hint: cards[req.params.id].hint })
})
router.get('/', (req, res) => {
res.render('card', {
cardFront: 'Default question',
hint: 'Default hint'
})
})
This may be fine while developing, but thinking of a real flashcard app I would likely want either a list of cards for you to click on one to start at (using res.json(cards)), or just have the app start at card 0 every time cardFront: cards[0].question
Afdol Rizki
23,158 Pointshi, let me try to answer, i think you should move the if statement so it located before the response object instead of inside of it
wildgoosestudent
11,274 PointsThis is probably what I would do (below is in pseudo code)
// if there is no :id in the params || the number doesn't exist in our database
// redirect to cards[0]
// else
//render the page it's asking for
Kenneth Kim
3,795 PointsKenneth Kim
3,795 PointsI'll just try to give my idea about it since i'm also learning this just now haha.
I believe if you do that, it should go the the default controller like the one with '/'. I think the best practice would be to provide a default controller for each route file that will handle the routing if there are no parameters in the request.
Maybe you could try adding 1 more route to the cards.js that can route the user to the Main menu or something like that. Something that it will be viewed as a default page if no parameter was given
Hope I was able to give you an idea or two :)