0
0
Expressframework~5 mins

DELETE route handling in Express

Choose your learning style9 modes available
Introduction

DELETE route handling lets your server remove data when a client asks for it. It helps keep your app's data up to date by deleting items.

When a user wants to delete their account from a website.
When removing a product from an online store's inventory.
When deleting a comment or post in a social media app.
When cleaning up old or unwanted records in a database.
Syntax
Express
app.delete('/path', (req, res) => {
  // code to delete resource
  res.send('Deleted successfully');
});

The app.delete method defines a route that listens for DELETE requests.

The callback function receives req (request) and res (response) objects to handle the request and send a response.

Examples
Deletes an item by its ID from the URL parameter.
Express
app.delete('/items/:id', (req, res) => {
  const id = req.params.id;
  // delete item with this id
  res.send(`Item ${id} deleted`);
});
Deletes all users when this route is called.
Express
app.delete('/users', (req, res) => {
  // delete all users
  res.send('All users deleted');
});
Sample Program

This Express app has a list of books. The DELETE route removes a book by its ID from the URL. If the book exists, it deletes and confirms. If not, it sends a 404 error.

Express
import express from 'express';

const app = express();
const port = 3000;

// Sample data
let books = [
  { id: 1, title: 'Book One' },
  { id: 2, title: 'Book Two' },
  { id: 3, title: 'Book Three' }
];

// DELETE route to remove a book by id
app.delete('/books/:id', (req, res) => {
  const bookId = Number(req.params.id);
  const index = books.findIndex(book => book.id === bookId);

  if (index !== -1) {
    books.splice(index, 1);
    res.status(200).send(`Book with id ${bookId} deleted.`);
  } else {
    res.status(404).send('Book not found.');
  }
});

app.listen(port, () => {
  console.log(`Server running on http://localhost:${port}`);
});
OutputSuccess
Important Notes

DELETE routes usually do not send back the deleted data, just a confirmation message.

Always check if the item to delete exists to avoid errors.

Use proper HTTP status codes like 200 for success and 404 if the item is not found.

Summary

DELETE routes handle requests to remove data from the server.

Use app.delete with a path and a callback function.

Always confirm deletion or handle errors if the item is missing.