Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

DELETE Requests in Node.js

Learn how to delete existing resources from a REST API using the DELETE HTTP method in Node.js and Express.

In a REST API, the DELETE method is used to remove an existing resource. For example, an application may allow users to delete a product using its ID.

Suppose a product has ID 1. When the client sends a DELETE request for that product, the server finds the product and removes it if it exists.

Remember: GET retrieves data, POST creates data, PUT or PATCH updates data, and DELETE removes data.

1. What Is a DELETE Request?

A DELETE request asks the server to remove a resource identified by the request URL. In a product API, the product ID is commonly passed as a route parameter.

HTTP
DELETE http://localhost:3000/api/products/1

In this example, the server attempts to delete the product whose ID is 1. If the deletion succeeds, the API can return a success message or an empty response, depending on its design.

Important: A DELETE request can permanently remove data when connected to a real database. Always verify the resource ID and apply appropriate authorization before deleting records.

2. Understanding the DELETE Route

Express provides the app.delete() method to handle DELETE requests. We can define a route containing an ID parameter and use that ID to locate the resource.

JavaScript
app.delete('/api/products/:id', (req, res) => {
    const id = Number(req.params.id);

    // Find the product using its ID
    // Delete the product if it exists
    // Return an appropriate response
});

Here is what each part means:

Code Purpose
app.delete() Registers a route for DELETE requests.
/api/products/:id Defines a URL containing a product ID parameter.
req.params.id Reads the ID supplied in the URL.
res.status() Sets the HTTP response status code.
res.json() Sends a JSON response to the client.

3. Complete Example: Deleting a Product

The following example creates an Express server with an in-memory product array. The DELETE route searches for a product by ID and removes it if found.

JavaScript
const express = require('express');

const app = express();

app.use(express.json());

let products = [
    { id: 1, name: 'Laptop', price: 50000 },
    { id: 2, name: 'Mobile', price: 20000 },
    { id: 3, name: 'Keyboard', price: 1500 }
];

// GET: Retrieve all products
app.get('/api/products', (req, res) => {
    res.status(200).json(products);
});

// DELETE: Remove a product by ID
app.delete('/api/products/:id', (req, res) => {
    const id = Number(req.params.id);

    if (!Number.isInteger(id) || id <= 0) {
        return res.status(400).json({
            message: 'Invalid product ID'
        });
    }

    const index = products.findIndex(
        product => product.id === id
    );

    if (index === -1) {
        return res.status(404).json({
            message: 'Product not found'
        });
    }

    const deletedProduct = products[index];

    products.splice(index, 1);

    res.status(200).json({
        message: 'Product deleted successfully',
        product: deletedProduct
    });
});

app.listen(3000, () => {
    console.log('Server running at http://localhost:3000');
});
This example uses an in-memory array. Deleted data is not stored permanently, and the original array will be restored when the server restarts. A database-backed API should perform the deletion through its database layer.

4. How Does the DELETE Request Work?

When the client sends a DELETE request, Express executes the matching route. The server reads the ID, validates it, searches for the product, and removes the matching record.

Client

Sends DELETE request with product ID

↓
Express DELETE Route

Reads the ID from req.params

↓
Validate and Find

Checks the ID and searches for the product

↓
Product Found

Remove the product and return success

Product Not Found

Return 404 Not Found

↓
HTTP Response

Sends the result to the client

5. Testing the DELETE Request

Start the Node.js server and open Postman to test the API. Select the DELETE method and enter the product URL.

Terminal
node app.js

Expected terminal output:

Output
Server running at http://localhost:3000

In Postman, configure the request as follows:

Setting Value
Method DELETE
URL http://localhost:3000/api/products/1
Request body Not required for this example

Expected response with status code 200 OK:

JSON
{
    "message": "Product deleted successfully",
    "product": {
        "id": 1,
        "name": "Laptop",
        "price": 50000
    }
}

To confirm the deletion, send a GET request to http://localhost:3000/api/products. The product with ID 1 will no longer appear in the returned array.

6. Handling Errors in DELETE Requests

A good REST API should handle invalid IDs and missing resources instead of returning a success response for every request.

Status Code Meaning Example
200 OK Deletion succeeded The product was removed and a JSON response is returned.
204 No Content Deletion succeeded without a response body The product was removed, and no response content is sent.
400 Bad Request The supplied ID is invalid The ID is not a positive integer.
404 Not Found The requested product does not exist No product matches the supplied ID.

For example, requesting an unknown product:

HTTP
DELETE http://localhost:3000/api/products/99

Example response with status code 404 Not Found:

JSON
{
    "message": "Product not found"
}

7. Important Points to Remember

  • Use app.delete() to create a DELETE route in Express.
  • Use req.params.id to read an ID from the URL.
  • Validate the ID before attempting deletion.
  • Check whether the resource exists before deleting it.
  • Return 404 when the requested resource does not exist.
  • Use 200 OK when returning a response body after deletion.
  • Use 204 No Content when the deletion succeeds and no body is returned.
  • Protect deletion routes with appropriate authentication and authorization.
  • Use a database for persistent data in real applications.

Summary

The DELETE HTTP method removes an existing resource from a REST API. In Express, we use app.delete() to define the route, req.params to read the resource ID, and appropriate HTTP status codes to communicate the result.

In the next lesson, we will learn how to validate incoming requests before processing them in a REST API.