0
0
Expressframework~30 mins

Separating routes into files in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Separating routes into files
📖 Scenario: You are building a simple Express web server. To keep your code clean and organized, you want to separate your routes into different files instead of putting all routes in one file.
🎯 Goal: Create an Express app that uses a separate route file for handling requests to /users. The main app file should import and use this route file.
📋 What You'll Learn
Create a route file named users.js that exports an Express router.
In users.js, define a GET route for / that sends the text 'User list'.
In the main app file app.js, import the users.js router.
Use the imported router in app.js for the path /users.
💡 Why This Matters
🌍 Real World
Separating routes into files helps keep your server code organized and easier to maintain as your app grows.
💼 Career
Many professional Express apps use routers in separate files to manage complexity and collaborate with teams.
Progress0 / 4 steps
1
Create the users route file
Create a file named users.js. Inside it, import express and create a router using express.Router(). Then define a GET route on '/' that sends the text 'User list'. Finally, export the router using module.exports = router.
Express
Need a hint?

Use express.Router() to create a router. Define routes on it like on an app. Export the router at the end.

2
Set up the main app file
In app.js, import express and create an app using express(). Also import the users.js router using require('./users'). Set the app to listen on port 3000.
Express
Need a hint?

Import express and create the app. Import the users router from './users'. Use app.listen(3000) to start the server.

3
Use the users router in the app
In app.js, use app.use('/users', usersRouter) to connect the imported usersRouter to the path /users.
Express
Need a hint?

Use app.use to mount the router on the /users path.

4
Add a root route to the app
In app.js, add a GET route on '/' that sends the text 'Welcome to the main page'.
Express
Need a hint?

Use app.get to define a route for the root path /.