Resource-based route organization helps keep your web app routes clear and easy to manage by grouping routes around data types or resources.
Resource-based route organization in Express
const express = require('express'); const router = express.Router(); // Define routes for a resource router.get('/', (req, res) => { /* list all resources */ }); router.post('/', (req, res) => { /* create new resource */ }); router.get('/:id', (req, res) => { /* get resource by id */ }); router.put('/:id', (req, res) => { /* update resource by id */ }); router.delete('/:id', (req, res) => { /* delete resource by id */ }); module.exports = router;
Use express.Router() to create a mini-router for each resource.
Routes use HTTP methods (GET, POST, PUT, DELETE) to represent actions on resources.
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}`); });
router.delete('/:id', (req, res) => { res.send(`Delete user ${req.params.id}`); });
This example creates a small Express app with resource-based routes for users. It groups all user-related routes under '/users'. Each route handles a common action like listing, creating, or deleting users.
const express = require('express'); const app = express(); const port = 3000; const usersRouter = express.Router(); // List all users usersRouter.get('/', (req, res) => { res.send('User list'); }); // Create a new user usersRouter.post('/', (req, res) => { res.send('User created'); }); // Get user by ID usersRouter.get('/:id', (req, res) => { res.send(`User details for ID: ${req.params.id}`); }); // Update user by ID usersRouter.put('/:id', (req, res) => { res.send(`User updated with ID: ${req.params.id}`); }); // Delete user by ID usersRouter.delete('/:id', (req, res) => { res.send(`User deleted with ID: ${req.params.id}`); }); // Use the usersRouter for routes starting with /users app.use('/users', usersRouter); app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });
Resource-based routes make your API predictable and easier to understand.
Use app.use('/resource', router) to mount resource routers.
Remember to handle errors and validate data in real apps.
Resource-based route organization groups routes by data type or resource.
Use Express Router to keep routes modular and clean.
Common HTTP methods map to actions on resources (GET, POST, PUT, DELETE).
Practice
Solution
Step 1: Understand resource-based route organization
Resource-based organization groups routes by the data or resource they manage, like users or products.Step 2: Identify the main benefit
This grouping helps keep code modular and easier to maintain by keeping related routes together.Final Answer:
It groups related routes together for better code organization. -> Option AQuick Check:
Grouping routes by resource = better organization [OK]
- Confusing route grouping with security features
- Assuming route organization affects server speed
- Thinking routes auto-generate HTML pages
books in Express?Solution
Step 1: Recall Express Router creation syntax
Express provides a Router() method on the express object to create modular route handlers.Step 2: Match the correct syntax
The correct syntax isexpress.Router(), notcreateRouter()ornew express.Router().Final Answer:
const booksRouter = express.Router(); -> Option CQuick Check:
Use express.Router() to create routers [OK]
- Using new keyword with Router
- Calling a non-existent createRouter method
- Using express.route instead of express.Router
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?Solution
Step 1: Identify the matching route for GET /users/42
The routerouter.get('/:id', ...)matches GET requests with a parameter after /users/.Step 2: Understand the response sent
The handler sends back the stringGet user 42using theidparameter from the URL.Final Answer:
Get user 42 -> Option BQuick Check:
GET /users/:id returns 'Get user {id}' [OK]
- Confusing POST and GET routes
- Ignoring route parameters in URL
- Assuming root path '/' matches /users/42
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'?Solution
Step 1: Understand router mounting path
The router is mounted at/api, so all routes inside it are prefixed with/api.Step 2: Match the route for getting item with id 5
The route/items/:idinside the router becomes/api/items/:idin the app.Final Answer:
/api/items/5 -> Option AQuick Check:
Router prefix + route path = full URL [OK]
- Ignoring the router prefix when calling URLs
- Using root path instead of mounted path
- Confusing POST and GET URLs
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?
Solution
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').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 withapp.use('/products', router).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.Final Answer:
const router = express.Router(); router.get('/', ...); router.post('/', ...); router.get('/:id', ...); router.put('/:id', ...); router.delete('/:id', ...); -> Option DQuick Check:
Use relative paths in router, mount on resource path [OK]
- Repeating resource name in every route inside router
- Using non-RESTful or verbose route paths
- Not mounting router on resource path
Ready to prove it?
Pass the test and this pattern moves unknown
