0
0
Expressframework~30 mins

Mounting routers with app.use in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Mounting Routers with app.use in Express
📖 Scenario: You are building a simple Express web server that handles different groups of routes separately. To keep your code organized, you want to use routers for different parts of your site.Think of routers like different departments in a store, each handling their own tasks. You will mount these routers on your main app using app.use.
🎯 Goal: Create two routers, one for /users and one for /products, then mount them on the main Express app using app.use.
📋 What You'll Learn
Create an Express app
Create a router called usersRouter with a GET route at / that sends 'Users Home'
Create a router called productsRouter with a GET route at / that sends 'Products Home'
Mount usersRouter on /users path using app.use
Mount productsRouter on /products path using app.use
💡 Why This Matters
🌍 Real World
In real web apps, routers help organize code by grouping related routes. For example, user-related routes go in one router, product-related routes in another.
💼 Career
Knowing how to mount routers with <code>app.use</code> is essential for building scalable Express applications and is a common task in backend web development jobs.
Progress0 / 4 steps
1
Create the Express app and usersRouter
Write code to create an Express app by calling express() and assign it to app. Then create a router by calling express.Router() and assign it to usersRouter. Add a GET route on usersRouter for path / that sends the text 'Users Home'.
Express
Need a hint?

Use const app = express() to create the app. Use const usersRouter = express.Router() to create the router. Then add a GET route on usersRouter with usersRouter.get('/', (req, res) => { res.send('Users Home') }).

2
Create the productsRouter with a GET route
Create a router called productsRouter by calling express.Router(). Add a GET route on productsRouter for path / that sends the text 'Products Home'.
Express
Need a hint?

Use const productsRouter = express.Router() to create the router. Then add a GET route on productsRouter with productsRouter.get('/', (req, res) => { res.send('Products Home') }).

3
Mount usersRouter on /users path
Use app.use to mount usersRouter on the path /users.
Express
Need a hint?

Use app.use('/users', usersRouter) to mount the router on the /users path.

4
Mount productsRouter on /products path
Use app.use to mount productsRouter on the path /products.
Express
Need a hint?

Use app.use('/products', productsRouter) to mount the router on the /products path.