JavaScript Express Basics Parameters, Query Strings, and Modularizing Routes Adding Links

Finley Williamson
Finley Williamson
11,375 Points

I know this doesn't work.. but why??

// running this code throws an error:
//Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

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

  if (side === "answer") {
    const {hint} = cards[id];  // here is where I think it's going wrong
  }

  const templateData = {text,hint};

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

If I understand correctly, because hint is being declared in a conditional, it throws an error when I try to reference it in the declaration of templateData.

However, my brain tells me hint should default to undefined, and run correctly.

Why then does the app throw this error?

Thank you in advance :D

1 Answer

Dale Severude
Dale Severude
Full Stack JavaScript Techdegree Graduate 71,275 Points

Hi Finley,

You are correct about the hint declaration causing an error. Since it is only defined within an if statement, then it only exists within that statement. Anything that tries to call hint from the outside will get an undeclared variable error which will crash JavaScript.

You need to remove this line from the conditional and operate the conditional another way.