0
0
Expressframework~30 mins

DELETE route handling in Express - Mini Project: Build & Apply

Choose your learning style9 modes available
DELETE Route Handling in Express
📖 Scenario: You are building a simple Express server to manage a list of books. Users can add, view, and delete books. Now, you will add the ability to delete a book by its ID using a DELETE route.
🎯 Goal: Create an Express DELETE route that removes a book from the list by its id.
📋 What You'll Learn
Create an array called books with three book objects, each having id and title properties.
Create a variable called bookIdToDelete and set it to 2.
Use the filter method on books to remove the book with id equal to bookIdToDelete.
Add an Express DELETE route at /books/:id that deletes the book with the given id from books.
💡 Why This Matters
🌍 Real World
Deleting items from a list via an API is common in web apps, such as removing products from a shopping cart or deleting user posts.
💼 Career
Understanding how to handle DELETE routes in Express is essential for backend web development roles that build RESTful APIs.
Progress0 / 4 steps
1
Create the initial books array
Create an array called books with these exact objects: { id: 1, title: 'Book One' }, { id: 2, title: 'Book Two' }, and { id: 3, title: 'Book Three' }.
Express
Need a hint?

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

2
Set the book ID to delete
Create a variable called bookIdToDelete and set it to the number 2.
Express
Need a hint?

Use const bookIdToDelete = 2; to store the ID.

3
Filter out the book to delete
Use the filter method on books to create a new array without the book whose id matches bookIdToDelete. Assign this new array back to books.
Express
Need a hint?

Use books = books.filter(book => book.id !== bookIdToDelete); to remove the book.

4
Add the Express DELETE route
Add an Express DELETE route at /books/:id. Inside the route handler, convert req.params.id to a number, then update books by filtering out the book with that id. Send a JSON response with { message: 'Book deleted' }.
Express
Need a hint?

Use app.delete('/books/:id', (req, res) => { ... }) and inside convert req.params.id to a number, then filter books, then send JSON response.