Bird
Raised Fist0
Expressframework~10 mins

Resource-based route organization in Express - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Resource-based route organization
Define resource name
↓
Create router object
↓
Add routes for CRUD operations
↓
GET /resource
↓
Export router
↓
Use router in main app
This flow shows how to organize routes by resource, defining all CRUD routes in one router and then using it in the main app.
Execution Sample
Express
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => res.send('List books'));
router.post('/', (req, res) => res.send('Create book'));

module.exports = router;
Defines GET and POST routes for the 'books' resource in a router, then exports it.
Execution Table
StepActionRoute RegisteredHandler BehaviorEffect
1Create router objectNo route yetNo handler yetRouter ready to add routes
2Add GET / routeGET /Responds with 'List books'GET / route available
3Add POST / routePOST /Responds with 'Create book'POST / route available
4Export routerRoutes readyHandlers readyRouter can be imported
5Use router in appRoutes active in appHandlers respond to requestsApp serves resource routes
6Request GET /booksMatches GET /Sends 'List books'Client receives list
7Request POST /booksMatches POST /Sends 'Create book'Client receives confirmation
8Request GET /books/123No route matches404 Not FoundClient gets error
💡 Execution stops after all routes are registered and requests handled or not matched.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4After Step 5
routerundefinedRouter with GET /Router with GET and POST /Router exportedRouter used in app
Key Moments - 2 Insights
Why does GET /books/123 return 404 even though we have routes for /books?
Because the router only defines routes for / (which is mounted at /books) and does not define a route with an id parameter like /:id. The route for /books/:id is missing, so the request does not match any route (see execution_table step 8).
Why do we create a router instead of adding routes directly to the app?
Creating a router groups all resource routes together, making code organized and reusable. Then we attach the router to the app once (see concept_flow steps 2-5).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the router state after step 3?
ARouter has GET / route only
BRouter is exported
CRouter has GET and POST / routes
DRouter is used in the app
💡 Hint
Check the 'Route Registered' column at step 3 in execution_table
At which step does the app start responding to requests?
AStep 4
BStep 5
CStep 6
DStep 7
💡 Hint
Look for when the router is used in the app in execution_table
If we add router.get('/:id', ...), what changes in the execution_table?
AStep 8 request GET /books/123 will match and respond
BStep 6 request GET /books will fail
CPOST /books route will be removed
DRouter will no longer export
💡 Hint
Consider how adding a route affects request matching in execution_table step 8
Concept Snapshot
Resource-based route organization in Express:
- Create a router with express.Router()
- Define CRUD routes for a resource (GET, POST, PUT, DELETE) on the router's root path
- Export the router
- Use router in main app with app.use('/resource', router)
- Keeps routes organized and reusable
Full Transcript
This visual execution trace shows how to organize routes in Express by resource. First, a router object is created. Then routes for the resource are added, such as GET / and POST / on the router. The router is exported and used in the main app mounted at /books. Requests to these routes match the handlers and respond accordingly. Requests to undefined routes like GET /books/123 return 404. This method groups related routes, making code cleaner and easier to maintain.

Practice

(1/5)
1. What is the main benefit of organizing routes by resource in an Express app?
easy
A. It groups related routes together for better code organization.
B. It automatically generates HTML pages for each resource.
C. It prevents users from accessing the API without a password.
D. It makes the server run faster by caching routes.

Solution

  1. Step 1: Understand resource-based route organization

    Resource-based organization groups routes by the data or resource they manage, like users or products.
  2. Step 2: Identify the main benefit

    This grouping helps keep code modular and easier to maintain by keeping related routes together.
  3. Final Answer:

    It groups related routes together for better code organization. -> Option A
  4. Quick Check:

    Grouping routes by resource = better organization [OK]
Hint: Think about grouping similar things together for neatness [OK]
Common Mistakes:
  • Confusing route grouping with security features
  • Assuming route organization affects server speed
  • Thinking routes auto-generate HTML pages
2. Which of the following is the correct way to create a router for a resource named books in Express?
easy
A. const booksRouter = new express.Router();
B. const booksRouter = express.createRouter();
C. const booksRouter = express.Router();
D. const booksRouter = express.route('books');

Solution

  1. Step 1: Recall Express Router creation syntax

    Express provides a Router() method on the express object to create modular route handlers.
  2. Step 2: Match the correct syntax

    The correct syntax is express.Router(), not createRouter() or new express.Router().
  3. Final Answer:

    const booksRouter = express.Router(); -> Option C
  4. Quick Check:

    Use express.Router() to create routers [OK]
Hint: Remember: Router is a method, not a constructor or create function [OK]
Common Mistakes:
  • Using new keyword with Router
  • Calling a non-existent createRouter method
  • Using express.route instead of express.Router
3. Given this Express router code for a users resource:
const express = require('express');
const router = express.Router();

router.get('/', (req, res) => res.send('List users'));
router.post('/', (req, res) => res.send('Create user'));
router.get('/:id', (req, res) => res.send(`Get user ${req.params.id}`));

module.exports = router;

What will be the response when a client sends a GET request to /users/42?
medium
A. List users
B. Get user 42
C. 404 Not Found
D. Create user

Solution

  1. Step 1: Identify the matching route for GET /users/42

    The route router.get('/:id', ...) matches GET requests with a parameter after /users/.
  2. Step 2: Understand the response sent

    The handler sends back the string Get user 42 using the id parameter from the URL.
  3. Final Answer:

    Get user 42 -> Option B
  4. Quick Check:

    GET /users/:id returns 'Get user {id}' [OK]
Hint: Match URL pattern with route parameters carefully [OK]
Common Mistakes:
  • Confusing POST and GET routes
  • Ignoring route parameters in URL
  • Assuming root path '/' matches /users/42
4. Consider this Express router code snippet:
const router = express.Router();

router.get('/items', (req, res) => res.send('All items'));
router.get('/items/:id', (req, res) => res.send(`Item ${req.params.id}`));
router.post('/items', (req, res) => res.send('Add item'));

module.exports = router;

When mounting this router in the main app with app.use('/api', router);, what is the correct URL to get the response 'Item 5'?
medium
A. /api/items/5
B. /items/5
C. /api/items
D. /items

Solution

  1. Step 1: Understand router mounting path

    The router is mounted at /api, so all routes inside it are prefixed with /api.
  2. Step 2: Match the route for getting item with id 5

    The route /items/:id inside the router becomes /api/items/:id in the app.
  3. Final Answer:

    /api/items/5 -> Option A
  4. Quick Check:

    Router prefix + route path = full URL [OK]
Hint: Add router prefix before route path when calling URLs [OK]
Common Mistakes:
  • Ignoring the router prefix when calling URLs
  • Using root path instead of mounted path
  • Confusing POST and GET URLs
5. You want to organize routes for a products resource using Express Router. You need to support listing all products, creating a product, getting a product by ID, updating a product by ID, and deleting a product by ID.

Which of the following router setups correctly implements all these routes following resource-based route organization?
hard
A. const router = express.Router(); router.get('/products', ...); router.post('/products', ...); router.get('/products/:id', ...); router.put('/products/:id', ...); router.delete('/products/:id', ...);
B. const router = express.Router(); router.get('/list', ...); router.post('/create', ...); router.get('/get/:id', ...); router.put('/update/:id', ...); router.delete('/delete/:id', ...);
C. const router = express.Router(); router.get('/products/all', ...); router.post('/products/new', ...); router.get('/products/get/:id', ...); router.put('/products/update/:id', ...); router.delete('/products/remove/:id', ...);
D. const router = express.Router(); router.get('/', ...); router.post('/', ...); router.get('/:id', ...); router.put('/:id', ...); router.delete('/:id', ...);

Solution

  1. Step 1: Understand resource-based route organization with routers

    When using Express Router for a resource, routes inside the router use relative paths like '/', '/:id' because the router is mounted on the resource path (e.g., '/products').
  2. Step 2: Identify the correct route paths

    const router = express.Router(); router.get('/', ...); router.post('/', ...); router.get('/:id', ...); router.put('/:id', ...); router.delete('/:id', ...); uses relative paths inside the router, which is the correct pattern. The router would be mounted with app.use('/products', router).
  3. Step 3: Compare with other options

    const router = express.Router(); router.get('/products', ...); router.post('/products', ...); router.get('/products/:id', ...); router.put('/products/:id', ...); router.delete('/products/:id', ...); repeats the resource name in every route, which is redundant inside a router. The remaining options use non-standard paths that don't follow REST conventions.
  4. Final Answer:

    const router = express.Router(); router.get('/', ...); router.post('/', ...); router.get('/:id', ...); router.put('/:id', ...); router.delete('/:id', ...); -> Option D
  5. Quick Check:

    Use relative paths in router, mount on resource path [OK]
Hint: Inside router, use relative paths; mount router on resource path [OK]
Common Mistakes:
  • Repeating resource name in every route inside router
  • Using non-RESTful or verbose route paths
  • Not mounting router on resource path
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard