An Express Router helps organize routes in your web app. It keeps your code clean and easy to manage.
Creating an Express Router
const express = require('express'); const router = express.Router(); router.get('/path', (req, res) => { res.send('Response text'); }); module.exports = router;
express.Router() to create a new router instance.const express = require('express'); const router = express.Router(); router.get('/hello', (req, res) => { res.send('Hello World'); }); module.exports = router;
const express = require('express'); const router = express.Router(); router.post('/submit', (req, res) => { res.send('Form submitted'); }); module.exports = router;
const express = require('express'); const router = express.Router(); router.use((req, res, next) => { console.log('Request received'); next(); }); router.get('/info', (req, res) => { res.send('Info page'); }); module.exports = router;
This program creates an Express app and a router. The router has a GET route at '/greet'. The app uses the router with the prefix '/api', so the full path is '/api/greet'. When you visit that URL, you see the greeting message.
const express = require('express'); const app = express(); const router = express.Router(); // Define a route on the router router.get('/greet', (req, res) => { res.send('Hello from the router!'); }); // Use the router with a prefix app.use('/api', router); // Start the server app.listen(3000, () => { console.log('Server running on http://localhost:3000'); });
Remember to export your router with module.exports so you can use it in your main app.
Mount routers on paths using app.use('/path', router) to organize routes under that path.
Routers can have their own middleware to handle requests before routes.
Express Router helps organize routes into smaller, manageable parts.
Create a router with express.Router() and define routes on it.
Use app.use() to mount routers under specific paths.
Practice
express.Router() in an Express app?Solution
Step 1: Understand what
This function creates a new router object that can hold routes separately from the main app.express.Router()doesStep 2: Identify the purpose of modular routes
Modular routes help organize code by grouping related routes, making the app easier to maintain.Final Answer:
To create a modular set of routes that can be mounted separately -> Option CQuick Check:
Router = modular routes [OK]
- Thinking router starts the server
- Confusing router with database handling
- Assuming router serves static files
Solution
Step 1: Recall the Express Router creation syntax
The correct method is callingRouter()as a function on the express object.Step 2: Check each option for syntax correctness
const router = express.Router(); usesexpress.Router()correctly. const router = new express.Router(); wrongly usesnew. const router = express.createRouter(); uses a non-existent method. const router = Router(); callsRouter()withoutexpress..Final Answer:
const router = express.Router(); -> Option AQuick Check:
Correct syntax = express.Router() [OK]
- Using new keyword with Router
- Calling a non-existent createRouter method
- Calling Router without express prefix
/api/users?
const express = require('express');
const app = express();
const router = express.Router();
router.get('/users', (req, res) => {
res.send('User list');
});
app.use('/api', router);
app.listen(3000);Solution
Step 1: Understand route mounting with
This mounts the router under the pathapp.use('/api', router)/api, so routes inside router are prefixed with/api.Step 2: Check the router route
The router handles GET requests to/users/users, so combined with the mount path, the full path is/api/users.Final Answer:
User list -> Option DQuick Check:
Mounted path + router path = /api/users [OK]
- Forgetting the mount path prefix
- Expecting route at root instead of /api
- Assuming router not mounted
const express = require('express');
const router = express.Router;
router.get('/info', (req, res) => {
res.send('Info page');
});
module.exports = router;Solution
Step 1: Check router creation syntax
The code usesexpress.Routerwithout parentheses, so it assigns the function itself, not an instance.Step 2: Confirm correct router instantiation
It should beexpress.Router()to create a router instance that supports route methods.Final Answer:
Missing parentheses when creating router instance -> Option AQuick Check:
Router needs () to create instance [OK]
- Forgetting () after express.Router
- Thinking trailing slash is required
- Confusing res.send with res.json
/users and one for /products. How do you correctly mount them in your Express app so that requests to /users/list and /products/list work as expected?Solution
Step 1: Understand router mounting with path prefixes
To handle routes under/usersand/products, mount each router with those paths usingapp.use().Step 2: Check each option for correct usage
app.use('/users', usersRouter); app.use('/products', productsRouter); mounts routers correctly with prefixes. app.use(usersRouter); app.use(productsRouter); mounts without prefixes, so routes won't be under desired paths. app.use('/list', usersRouter); app.use('/list', productsRouter); mounts both under/list, causing conflicts. app.get('/users', usersRouter); app.get('/products', productsRouter); usesapp.getincorrectly with routers.Final Answer:
app.use('/users', usersRouter); app.use('/products', productsRouter); -> Option BQuick Check:
Mount routers with correct path prefixes [OK]
- Mounting routers without path prefix
- Using app.get instead of app.use for routers
- Mounting multiple routers on same path
Ready to prove it?
Pass the test and this pattern moves unknown
