Route Parameters
Part of the Express Basics section of Coddy's Node.js journey. Lesson 4 of 20.
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
EasyGET /recipes/:idanswers the title of the recipe with that id.- An unknown id answers
404withNo such recipe.
Send GET /recipes/2, then GET /recipes/99.
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');
});
This lesson includes a short quiz. Start the lesson to answer it and track your progress.