JavaScript Express Basics Parameters, Query Strings, and Modularizing Routes Using Data and Route Parameters

Michael Williams
PRO
Michael Williams
Pro Student 8,057 Points

Does the URL parameter always have to be named 'id'?

Here's the code from the exercise. It wasn't clear if id could be called anything since it's being treated like a variable or if it's hardwired in as an id property.

const express = require ('express');
const router = express.Router();
const { data } = require('../data/flashcardData.json'); //equivalent of const data = require('../data/flashcardData.json').data;
const { cards } = data; //curly braces mean that cards = data.cards >> const cards = data.cards; 


router.get('/:id', (req, res) => {
    res.render('card', { 
        prompt: cards[req.params.id].question,
        hint: cards[req.params.id].hint
    });
});

module.exports = router;

2 Answers

Hi Michael,

You are right in thinking the route parameter acts like a variable. You can call it whatever you like, just make sure you update any references to it.

// Route
router.get('/:blah')

// To access blah use:
req.params.blah

Example:

router.get('/:blah', (req, res) => {
    res.render('card', { 
        prompt: cards[req.params.blah].question
        // ...
    });
});

Hope this helps :)