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

Vincent Doyle
Vincent Doyle
18,208 Points

The answer side doesn't link to the question.

Everything works perfectly but when I go to the answer link http://localhost:3000/cards/3?side=answer it doesn't give me a link redirecting me to the question.

cards.js

const express = require('express'); const router = express.Router(); const { data } = require('../data/flashcardData.json'); const { cards } = data;

router.get( '/', ( req, res ) => { const numberOfCards = cards.length; const flashcardId = Math.floor( Math.random() * numberOfCards ); res.redirect( /cards/${flashcardId} ) });

router.get('/:id', (req, res) => { const { side } = req.query; const { id } = req.params;

if ( !side ) {
    return res.redirect(`/cards/${id}?side=question`);
}
const name = req.cookies.username;
const text = cards[id][side];
const { hint } = cards[id];

const templateData = { id, text, name };

if ( side === 'question' ) {
    templateData.hint = hint;
    templateData.sideToShow = 'answer';
    templateData.sideToShowDisplay = 'Answer';      
} else if ( side === 'answer' ) {
    templateData.sideToShow = 'question';
    templateData.sideToShowDisplay = 'Question';
}

res.render('card', templateData);

});

module.exports = router;

card.pug

extends layout.pug

block content section#content h2= text if hint p i Hint: #{hint} a(href=${id}?side=${sideToShow})= sideToShowDisplay br a(href='/cards') Next card

1 Answer

You may have already solved this. Currently you are only checking of side has no value / undefined. You need to to also check if the value is either answer or question because you don't want to redirect on either of those values.

    if (!side || !(side === 'answer' || side === 'question' ) ) {
        res.redirect(`/cards/${id}?side=question`);
    }