Menu
CoddyTech

Express Router

Part of the Express Basics section of Coddy's Node.js journey. Lesson 16 of 20.

server.js now holds pages, API routes and middleware, and it keeps growing.

// routes/books.js
const router = express.Router();
router.get('/', (req, res) => res.json(books));
router.get('/:isbn', (req, res) => res.json(findBook(req.params.isbn)));
export default router;

// server.js
app.use('/api/books', booksRouter);

express.Router() makes a small app with routes of its own, kept in its own file. app.use('/api/books', booksRouter) mounts it: the router's / answers GET /api/books, and its /:isbn answers GET /api/books/9780141439518. The prefix is written once, in app.use. Errors thrown inside a router still reach the app's error handler.

The new file routes/recipes.js already has one route, /tags.

challenge icon

Challenge

Easy
  • Move the four /api/recipes routes from server.js into routes/recipes.js, below /tags.
  • Mount the router at /api/recipes.

Send GET /api/recipes/tags, GET /api/recipes/2 and GET /api/recipes/2/scale?by=lots.

Try it yourself

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

const router = express.Router();

// Every tag, once, in alphabetical order.
router.get('/tags', (req, res) => {
    const tags = new Set(recipes.flatMap((recipe) => recipe.tags));
    res.json([...tags].sort());
});

// Move the /api/recipes routes from server.js here, below /tags.
// Inside a router, paths are relative to where it is mounted.

export default router;
quiz iconTest yourself

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

All lessons in Express Basics