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 Linking Around the Application

Lewis Marshall
Lewis Marshall
22,673 Points

My solution to handle invalid query string key 'side' value

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

  // checks the side value is included in the array 
  const invalidQueryString = !["question", "answer"].includes(side); 

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

    const templateData = { text, id, side, name };

    if (side === "question") {
      templateData.hint = hint;
    } 

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

1 Answer

Trevor Maltbie
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Trevor Maltbie
Full Stack JavaScript Techdegree Graduate 17,021 Points

Good thinking, Lewis. Using the includes method is a good approach.

I had thought of something similar:

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

However, this leads to an infinite amount of redirects and crashes the site.

EDIT: I just realized that this is failing because if || operator. If it's not answer but it is question it just keeps bouncing back and forth.

The solution is to make use && operator.