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:

  1. Express Setup: Import Express and create an instance of the app.

  2. Main Route: Set up a basic route handling a GET request to the root path ('/').

  3. Nested Route: Create a separate router using express.Router() to handle nested routes. In this case, it handles a GET request to '/nested'.

  4. Mounting Nested Route: Use app.use() to mount the nested router to a specific path '/main'. This means that any routes defined in nestedRouter will be accessible under '/main'.

  5. 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'.