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

Karen Shea
Karen Shea
13,731 Points

RangeError [ERR_HTTP_INVALID_STATUS_CODE]: Invalid status code: undefined Pretty sure the issue is in cards.js.

Pretty sure the issue is in cards.js.

Here is the entirety of that file:

```const express = require('express'); const router = express.Router(); const { data } = require('../data/flashcarddata.json'); const { cards } = data;

router.get('/', (req, res) => { const numberOfCards = cards.length; const flashcardId = Math.floor(Math.random() * numberOfCards); res.redirect(/cards/${flashcardId}); });

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

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

const templateData = { id, text, name };

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

});

module.exports = router;```

2 Answers

One problem is that you are defining side as const and later reassigning it... instead you should define side with let

    let {side} = req.query;
Kevin Gates
Kevin Gates
14,701 Points

Okay, I've had to deal with this. It's requiring an HTTP status code, so I've used 302. So if you change from this:

res.redirect(/cards/${flashcardId});

to this

res.status(302).redirect(`/cards/${flashcardId}`);

it should work.

Also though, for me the behavior is different. If I'm in the sub-folder already it sometimes results in cards/cards/3...

So to get this to work localhost:3000/cards/ and localhost:3000/cards/3 to work, I need to make my code this:

const express = require('express');
const router = express.Router();
const { data } = require('../data/flashcardData.json');
const { cards } = data;

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

    if ( !side ) {
        res.status(302).redirect(`${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);
});

router.get('/', (req, res) => {
    const totalCards = cards.length;
    const randomCard = Math.floor(Math.random()*totalCards);
    res.status(302).redirect(`${randomCard}?side=question`);
});


module.exports = router;