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

JavaScript Express Basics Parameters, Query Strings, and Modularizing Routes Randomize Cards

Damian McCarthy
Damian McCarthy
3,656 Points

The ID variable comes up as undefined when I click the link, The other variable works fine though

http://localhost:8080/cards/undefined?side=answer

extends layout.pug

block content
    section#content

      h2= text

      if hint
        p
          i Hint: #{hint}

      a(href='/' + `${id}?side=${sideToShow}`)= sideToShowDisplay
const express = require('express');
const router = express.Router();
const { data } = require('../data/flashcardData.json');
const cards = data.cards;

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

    const templateData = { text };
    console.log(id);
    if (side === 'question') {
        templateData.hint = hint;
        templateData.sideToShow= 'answer';
        templateData.sideToShowDisplay= 'Answer';
    } else if (side === 'answer') {
        templateData.sideToShow= 'question';
        templateData.sideToShowDisplay= 'Question';
    }

    res.render('cards', templateData);
});

module.exports = router;
Steven Parker
Steven Parker
229,744 Points

Note: Links to "localhost" only work on your own computer and cannot be shared with other students.

Damian McCarthy
Damian McCarthy
3,656 Points

I am Aware it Doesn't really matter that it says local host I was just showing the issue I was having which when the id variable is called it comes out undefined in the URL. The other portion of the URL's Variable works and when I console log it, it works.

1 Answer

You need to pass id into your render() call. Put it inside the templateData object,

const templateData = { text, id };

and you should be able to reference it from the .pug template i.e.

a(href=`${id}?side=${otherSide}`)

And remove the '/' before the ${id}, that was screwing mine up.

I got it to work without the id entirely. My code looks like this:

a(href=`?side=${otherSide}`)
Damian McCarthy
Damian McCarthy
3,656 Points

Yeah, I already figured this one out.