0
0
Expressframework~30 mins

Resource-based route organization in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
Resource-based route organization in Express
📖 Scenario: You are building a simple web server for a bookstore. You want to organize your routes by resource type to keep your code clean and easy to maintain.
🎯 Goal: Create an Express app that organizes routes for the books resource using resource-based route organization. You will set up the initial data, configure a router, add core route handlers, and complete the app to listen on a port.
📋 What You'll Learn
Create an Express app with a books array containing book objects
Create a router for books routes
Add GET route handlers for /books and /books/:id
Make the app use the books router under the /books path
Start the server listening on port 3000
💡 Why This Matters
🌍 Real World
Organizing routes by resource helps keep server code clean and maintainable, especially as projects grow.
💼 Career
Understanding Express routers and resource-based route organization is essential for backend web development jobs using Node.js.
Progress0 / 4 steps
1
Set up initial data and Express app
Create an Express app by requiring express and calling express(). Then create a books array with these exact objects: { id: 1, title: '1984' }, { id: 2, title: 'Brave New World' }, and { id: 3, title: 'Fahrenheit 451' }.
Express
Need a hint?

Remember to require Express and call it to create your app. Then create the books array with the exact objects.

2
Create a router for books
Create a router by calling express.Router() and assign it to a variable called booksRouter.
Express
Need a hint?

Use express.Router() to create a router for the books resource.

3
Add GET routes to the books router
Add a GET route handler on booksRouter for path '/' that sends the full books array as JSON. Also add a GET route handler on booksRouter for path '/:id' that finds a book by id from books and sends it as JSON. Use req.params.id and convert it to a number to find the book.
Express
Need a hint?

Use booksRouter.get to add route handlers. Use res.json() to send JSON responses.

4
Use the router and start the server
Make the Express app use booksRouter for the path '/books' by calling app.use('/books', booksRouter). Then start the server listening on port 3000 using app.listen(3000).
Express
Need a hint?

Use app.use to connect the router and app.listen to start the server.