Menu
CoddyTech

More Routes

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

A site has more than one page, so the server needs a route for each path.

app.get('/books', (req, res) => {
    res.send('12 books on the shelf');
});

app.get('/opening-hours', (req, res) => {
    res.send('Monday to Friday, 10 to 6');
});

Express reads the path of each request and calls the route with that path: GET /books reaches the first function, GET /opening-hours the second. A path with no route gets Express's own 404 page. A route's path always starts with /.

Recipe Box is back, with a data.js file holding four recipes and a /recipes route that lists their titles.

challenge icon

Challenge

Easy

Recipe Box needs an About page next to the home page and the recipe list.

  1. In server.js, where the comment says // Add the /about page here., add a route for the path /about. It sends this sentence, full stop included: Recipe Box collects family recipes.
  2. Leave the / and /recipes routes as they are.

Try it: Press Run and send /about. You should see Recipe Box collects family recipes. Send /recipes: the four recipe titles, one per line. Then send /about-us. No route has that path, so Express responds with status 404 and Cannot GET /about-us. The list of paths in the request bar shows the routes your app has.

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

// Add the /about page here.

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

All lessons in Express Basics

Practice on your own: Express playground