0
0
Expressframework~30 mins

Controller pattern for route handlers in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Controller pattern for route handlers
📖 Scenario: You are building a simple Express web server that manages a list of books. To keep your code clean and organized, you want to separate the route handling logic into a controller.
🎯 Goal: Create an Express server with a controller pattern where route handlers are defined in a separate controller object. You will set up the data, configure a controller, connect routes to controller methods, and complete the server setup.
📋 What You'll Learn
Create an array called books with three book objects, each having id and title properties
Create a controller object called bookController with a method getAllBooks that sends the books array as JSON
Set up an Express route GET /books that uses bookController.getAllBooks as the handler
Complete the Express server setup to listen on port 3000
💡 Why This Matters
🌍 Real World
Separating route logic into controllers helps keep Express apps organized and easier to maintain, especially as they grow.
💼 Career
Understanding the controller pattern is essential for backend developers working with Express or similar web frameworks.
Progress0 / 4 steps
1
DATA SETUP: Create the books array
Create an array called books with these exact objects: { id: 1, title: 'The Hobbit' }, { id: 2, title: '1984' }, and { id: 3, title: 'Pride and Prejudice' }.
Express
Need a hint?

Use const books = [ ... ] with three objects inside the array.

2
CONFIGURATION: Create the bookController object
Create a constant object called bookController with a method getAllBooks that takes req and res parameters and sends the books array as JSON using res.json(books).
Express
Need a hint?

Define bookController as an object with a method getAllBooks that calls res.json(books).

3
CORE LOGIC: Set up the Express route using the controller
Import Express, create an app with express(), and add a route GET /books that uses bookController.getAllBooks as the handler.
Express
Need a hint?

Use const app = express() and app.get('/books', bookController.getAllBooks).

4
COMPLETION: Start the Express server
Add app.listen(3000) to start the server on port 3000.
Express
Need a hint?

Use app.listen(3000) to start the server.