0
0
Expressframework~30 mins

Creating an Express Router - Try It Yourself

Choose your learning style9 modes available
Creating an Express Router
📖 Scenario: You are building a simple web server using Express.js. To keep your code organized, you want to separate the routes related to users into their own router.
🎯 Goal: Create an Express router for user-related routes and connect it to the main Express app.
📋 What You'll Learn
Create an Express router instance
Define a GET route on the router for path '/' that sends 'User list' as response
Create an Express app instance
Use the router on the '/users' path in the app
💡 Why This Matters
🌍 Real World
Express routers help organize routes in web servers by grouping related routes together. This makes code easier to read and maintain.
💼 Career
Knowing how to create and use Express routers is essential for backend developers working with Node.js and Express to build scalable web applications.
Progress0 / 4 steps
1
Set up Express and create a router
Write code to import Express and create a router instance called userRouter.
Express
Need a hint?

Use require('express') to import Express and express.Router() to create the router.

2
Add a GET route to the router
Add a GET route on userRouter for path '/' that sends the text 'User list' as the response.
Express
Need a hint?

Use userRouter.get('/', (req, res) => { res.send('User list'); }) to define the route.

3
Create the Express app
Create an Express app instance called app by calling express().
Express
Need a hint?

Call express() and assign it to app.

4
Use the router in the app
Connect the userRouter to the app so that all routes in userRouter are served under the path '/users'.
Express
Need a hint?

Use app.use('/users', userRouter) to mount the router.