Mounting routers with app.use helps organize your web app by grouping related routes together. It keeps your code clean and easier to manage.
0
0
Mounting routers with app.use in Express
Introduction
You want to separate user-related routes from product-related routes in your app.
You have many routes and want to split them into smaller files for better organization.
You want to reuse a set of routes in different parts of your app.
You want to add middleware to a group of routes easily.
You want to keep your main app file simple and clean.
Syntax
Express
const express = require('express'); const app = express(); const router = express.Router(); // Define routes on the router router.get('/path', (req, res) => { res.send('response'); }); // Mount the router on a path app.use('/basepath', router);
app.use mounts the router at the specified base path.
Routes inside the router will be relative to the base path.
Examples
This mounts
userRouter at /users. Visiting /users shows 'User home'.Express
const express = require('express'); const app = express(); const userRouter = express.Router(); userRouter.get('/', (req, res) => { res.send('User home'); }); app.use('/users', userRouter);
This mounts
productRouter at /products. Visiting /products/list shows 'Product list'.Express
const express = require('express'); const app = express(); const productRouter = express.Router(); productRouter.get('/list', (req, res) => { res.send('Product list'); }); app.use('/products', productRouter);
Sample Program
This example creates a blogRouter with two routes: '/' and '/post'. It mounts the router at '/blog'. So, visiting '/blog' shows 'Welcome to the blog home' and '/blog/post' shows 'This is a blog post'.
Express
const express = require('express'); const app = express(); const port = 3000; // Create a router for blog routes const blogRouter = express.Router(); // Define a route on blogRouter blogRouter.get('/', (req, res) => { res.send('Welcome to the blog home'); }); blogRouter.get('/post', (req, res) => { res.send('This is a blog post'); }); // Mount blogRouter at /blog app.use('/blog', blogRouter); // Start the server app.listen(port, () => { console.log(`Server running on http://localhost:${port}`); });
OutputSuccess
Important Notes
Remember that the paths inside the router are relative to the mount path.
You can mount multiple routers on different paths to keep your app organized.
Use app.use to add middleware or routers to your app.
Summary
Mounting routers with app.use helps organize routes by grouping them under a base path.
It makes your code cleaner and easier to maintain.
Routes inside routers are relative to the path you mount them on.