Nested Routes
Part of the Express Basics section of Coddy's Node.js journey. Lesson 17 of 20.
Reviews belong to one recipe, so their URLs live under it: /api/recipes/2/reviews.
const chapters = express.Router({ mergeParams: true });
chapters.get('/', (req, res) => {
res.json(chaptersOf(req.params.isbn));
});
app.use('/api/books/:isbn/chapters', chapters);A router's req.params holds only the parameters of its own paths. The :isbn in the mount path belongs to the app, so inside the router it is undefined, unless the router is made with mergeParams: true.
routes/reviews.js is ready, with a reviews object and a hasRecipe(id) helper.
Challenge
EasyGET /api/recipes/:id/reviewsanswers that recipe's reviews,[]at first.POSTwith{ "stars", "text" }adds one and answers201with it.- An unknown recipe:
404with{ "error": "No such recipe" }.
Post a review for recipe 1, then send GET /api/recipes/1/reviews and GET /api/recipes/99/reviews.
Try it yourself
import express from 'express';
import { recipes } from '../data.js';
// Reviews by recipe id, like { 1: [{ stars: 5, text: 'Lovely' }] }.
const reviews = {};
const hasRecipe = (id) => recipes.some((recipe) => recipe.id === Number(id));
const router = express.Router();
// GET / lists a recipe's reviews. POST / adds one.
export default router;