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

Maria Te
Maria Te
8,517 Points

I have an error when I type localhost:4000/cards:0

I am following the video but my code doesn't work

routes/cards.pug

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

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

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

views/cards.pug

extends layout.pug

block content
    section#content
        form(action="/cards", method="post")
            h3= prompt
            if hint 
                p 
                    i Hint: #{hint}
            h3 
                i Answer: #{answer}
            button(type="submit") Next

2 Answers

Maria Te
Maria Te
8,517 Points

Oh wait, now I have it. You have to do localhost:4000/cards/0

Maria Te
Maria Te
8,517 Points

data/flashcard.json

{
    "data": {
        "title": "Animal FlashCards",
        "cards": [
            {
                "question": "What's the smallest animal on Earth?",
                "hint": "It lives in the ocean",
                "answer": "Water Bear"
            },
            {
                "question": "How many legs does a milipede have?",
                "hint": "Number from 100 - 1000",
                "answer": "400"
            },
            {
                "question": "How big is a baby kangaroo?",
                "hint": "Less than 1 foot",
                "answer": "2 cm"
            },
            {
                "question": "What's the loudest animal in the world?",
                "hint": "It can't walk or fly",
                "answer": "Sperm Whale"
            },
            {
                "question": "How fast can a cheetah run?",
                "hint": "Number from 10 - 200",
                "answer": "70 mph"
            },
            {
                "question": "What's the longest living animal?",
                "hint": "It's a warm-blooded mammal",
                "answer": "Bowhead Whale"
            },
            {
                "question": "How many times can a woodpecker peck per sec?",
                "hint": "Number from 1 - 50",
                "answer": "20 times"
            },
            {
                "question": "How many years old can a mouse be?",
                "hint": "Number from 1 - 30",
                "answer": "2 years"
            },
            {
                "question": "Which animal is immortal?",
                "hint": "Turtles eat them",
                "answer": "Immortal Jellyfish"
            }
        ]
    }
}