Hello, aspiring programmer! We've learned how to read data using GET and send new data using POST in our backend journey. Now, let's discover how to update and delete data via PUT and DELETE HTTP methods. With these, you'll be able to adjust or remove any to-do item in our Todo List, making it fully interactive!
The PUT
method updates existing server data. Let's say a to-do item says, "Buy groceries." But we remembered we don't need groceries; instead, we need toothpaste. So we need to update our to-do item to "Buy toothpaste," and here's where the PUT
method comes in handy!
With Express.js, we can update our "Buy groceries" to-do item like this:
JavaScript1// Handle a PUT request to update a to-do 2app.put('/api/todo/:id', (req, res) => { 3 // Find the to-do item by ID 4 const todo = todos.find(c => c.id === parseInt(req.params.id)); 5 6 // Update the title of the to-do 7 todo.title = req.body.title; 8 9 // Respond with the updated to-do item 10 res.send(todo); 11});
In /api/todo/:id
, :id
is a parameter that stands for the specific ID of the to-do item we want to update.
The DELETE
method allows us to delete existing server data. Referencing our to-do list, if a task like "Buy toothpaste" is done, we can remove it:
JavaScript1// Handle a DELETE request to delete a to-do 2app.delete('/api/todo/:id', (req, res) => { 3 // Find the to-do item by ID 4 const todo = todos.find(c => c.id === parseInt(req.params.id)); 5 6 // Remove the to-do from the list 7 const index = todos.indexOf(todo); 8 todos.splice(index, 1); 9 10 // Respond with the deleted to-do item 11 res.send(todo); 12});
With app.delete()
, our to-do items can be removed — a critical feature for any real-world application.
Great work today! We've added two more skills to our toolset — the PUT and DELETE HTTP methods, which help us update and delete data. Having explored CRUD operations, we've made our Todo List app far more useful and flexible!
Now, get ready for the upcoming hands-on practice. Remember, practice cements knowledge and sharpens skills. So keep at it, and great things will come!