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

Lewis Marshall
Lewis Marshall
22,672 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,005 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.