JavaScript Express Basics Parameters, Query Strings, and Modularizing Routes Linking Around the Application

Ismayil Aliyev
Ismayil Aliyev
18,529 Points

Error: Cannot set headers after they are sent to client (for redirecting when there is no side variable)

In the redirecting challenge, I wrote code exact as in video and it works. But command line gives me such kind of message:

Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client

Please, help me to understand why I got such a message even if app works properly, and how can I solve it or should I?

Michael Hulet
Michael Hulet
Treehouse Moderator 46,831 Points

You've called res.set (or a related method) sometime after response.send, which isn't allowed. We'd need to know more about your code to point to a specific line

1 Answer

Ismayil Aliyev
Ismayil Aliyev
18,529 Points

Dear friends, I could figure out why cmd was giving me such kind of error.

router.get('/:id', (req, res) => {
    const { side } = req.query;
    const { id } = req.params;
    if(!side){
      return res.redirect(`/cards/${id}?side=question`)
    }
    const text = cards[id][side];
    const { hint } = cards[id];

    const templateData = { id, text };

    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);
});

The main reason was router.get() method couldn't finish its work because of redirecting. I found solution in writing return value before redirecting. Thanks a lot for your attention :) .

Victoria Medley
Victoria Medley
17,085 Points

What do you mean by this? Where did you put the return value and what did you write exactly? Could you post a snippet of the completed code? I am stuck on the same issue, I tried what you said but cannot figure it out.

Gabbie Metheny
Gabbie Metheny
33,668 Points

Andrew addresses this a couple videos later, here. Basically, the rest of the router.get() function tries to execute, so we're trying to redirect and render simultaneously. Attempting to render after the redirect is what's causing the console error. Using the return keyword breaks us out of the router.get() function when we redirect, before the res.render().