More Routes
Part of the Express Basics section of Coddy's Node.js journey. Lesson 3 of 20.
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
EasyAdd a page /about that answers Recipe Box collects family recipes.
Run, send GET /about, then send GET /about-us and read the routes Express lists.
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');
});