nesting express routes
Certainly! Here's an example of nesting Express routes:
const express = require('express');
const app = express();
// Main route
app.get('/', (req, res) => {
res.send('Welcome to the main route!');
});
// Nested route
const nestedRouter = express.Router();
nestedRouter.get('/nested', (req, res) => {
res.send('Welcome to the nested route!');
});
// Mounting the nested route
app.use('/main', nestedRouter);
// Starting the server
const PORT = 3000;
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
Explanation:
Express Setup: Import Express and create an instance of the app.
Main Route: Set up a basic route handling a GET request to the root path ('/').
Nested Route: Create a separate router using
express.Router()
to handle nested routes. In this case, it handles a GET request to '/nested'.Mounting Nested Route: Use
app.use()
to mount the nested router to a specific path '/main'. This means that any routes defined innestedRouter
will be accessible under '/main'.Server Start: Set up the server to listen on port 3000 and log a message once it's running.
This structure allows for organizing routes into logical groups, making the code more modular and maintainable. The nested route is accessed as '/main/nested'.