Menu
CoddyTech

Route Parameters

Part of the Express Basics section of Coddy's Node.js journey. Lesson 4 of 23.

Recipe Box will hold many recipes, and one route per recipe would never end.

app.get('/weather/:city', (req, res) => {
    res.send('Forecast for ' + req.params.city);
});

A path part that starts with a colon is a route parameter: it matches any value, and Express puts that value in req.params. GET /weather/oslo sends Forecast for oslo.

A parameter is always a string. GET /rooms/12 gives '12', and '12' === 12 is false, so convert it with Number(...) before comparing it with numbers.

When the thing asked for does not exist, answer status 404: res.status(404).send('No such city') sets the status, then sends.

challenge icon

Challenge

Easy

Each recipe gets its own page, at a path that holds its id: /recipes/1, /recipes/2, and so on.

  1. In server.js, add one route for /recipes/:id. It finds the recipe in recipes (from data.js) whose id matches the id in the path. It sends only that recipe's title, as text: /recipes/2 sends Pancakes.
  2. The id from the path is a string, and the ids in data.js are numbers, so convert it before you compare.
  3. When no recipe has that id, set the status to 404 and send the text No such recipe.

Try it: Press Run and send /recipes/2. You should see Pancakes with status 200. Send /recipes/4: Fish & Chips. Send /recipes/99: No such recipe with status 404.

Try it yourself

import express from 'express';
import { recipes } from './data.js';

const app = express();

app.get('/', (req, res) => {
    res.send('Welcome to Recipe Box');
});

// type('text') sends plain text, so each title shows on its own line.
app.get('/recipes', (req, res) => {
    res.type('text').send(recipes.map((recipe) => recipe.title).join('\n'));
});

app.get('/about', (req, res) => {
    res.send('Recipe Box collects family recipes.');
});

app.listen(3000, () => {
    console.log('Recipe Box is running on port 3000');
});
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Express Basics

Practice on your own: Express playground