Different HTTP Methods and their Functionalities

HTTP (Hypertext Transfer Protocol) defines several methods also referred to as HTTP which indicate the desired action to be performed on a resource. Here is the list of some of the most commonly used HTTP methods:

1. GET

2. POST

3. HEAD

4. PUT

5. DELETE

6. PATCH

7. OPTIONS

8. TRACE


Different HTTP Methods and their Functionalities

1. GET

The GET method is used to request data or information from the given server using a given URI. GET method is used to only retrieve the data from the server and it should have no other effect on the data.

Example

const http = require('http');
const PORT = 5000;

// Create a simple server
const server = http.createServer((req, res) => {
    // Check if the incoming request method is GET
    if (req.method === 'GET') {
        // Set the response header
        res.writeHead(200, { 'Content-Type': 'text/html' });

        // Send a simple response
        res.end('Hey, this is a GET request from the user!');
    }
    else {
        // If the request method is not GET, respond with a 405
        res.writeHead(405, { 'Content-Type': 'text/plain' });
        res.end('Method Not Allowed');
    }
});

// Set the server to listen on a port
server.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
});


2. POST

POST request is used to send data from the user to the server. This is often used when a user submits a form on the web page. For example, student registration, customer information, file upload, etc. using HTML forms.

Example

const http = require('http');
const PORT = 5000;

const server = http.createServer((req, res) => {
    if (req.method === 'POST') {
        let data = '';

        // Handle data chunks as they come in
        req.on('data', chunk => {
            data += chunk;
        });

        // When all data is received
        req.on('end', () => {
            // Parse the received JSON data
            const jsonData = JSON.parse(data);

            // Perform some processing with the data (in this case, just echoing it back)
            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ message: 'Data received successfully', data: jsonData }));
        });
    }
    else {
        // If the request method is not POST, respond with a 405 Method
        res.writeHead(405, { 'Content-Type': 'text/plain' });
        res.end('Method Not Allowed');
    }
});

server.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
});

3. HEAD

The HEAD method is same as GET, but it is used to request only status line and header section without the actual body content. In other words it's request to identical to a GET request but without the response body.

Example

const http = require('http');
const PORT = 5000;

const server = http.createServer((req, res) => {
    if (req.method === 'HEAD') {
        // Respond with headers only, no body
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end();
    }
    else {
        // If the request method is not HEAD, respond with a 405 Method
        res.writeHead(405, { 'Content-Type': 'text/plain' });
        res.end('Method Not Allowed');
    }
});

server.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
});


4. PUT

The PUT method is used to update the already existing resource or to create a new resource if it does not exist at a specified URL. In the other words, PUT method replaces all current the representations of the target resource with new uploaded content.

Example

const http = require('http');
const PORT = 5000;

// In-memory data store for illustration
const dataStore = {};

const server = http.createServer((req, res) => {
    if (req.method === 'PUT') {
        let data = '';

        // Handle data chunks as they come in
        req.on('data', chunk => {
            data += chunk;
        });

        // When all data is received
        req.on('end', () => {
            // Extract the resource identifier from the URL
            const resourceId = req.url.slice(1); // Assuming the resource identifier is in the path

            // Update or create the resource in the data store
            dataStore[resourceId] = JSON.parse(data);

            // Respond with a success status
            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ message: 'Resource updated successfully!' }));
        });
    }
    else {
        // If the request method is not PUT, respond with a 405 Method
        res.writeHead(405, { 'Content-Type': 'text/plain' });
        res.end('Method Not Allowed!');
    }
});

server.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
});


5. DELETE

The DELETE HTTP Method is used to request the deletion of a resource at a specified URL. This method is used when the client wants to delete a resource on the server.

Example

const http = require('http');
const PORT = 5000;

// In-memory data store for illustration
const dataStore = {};

const server = http.createServer((req, res) => {
    if (req.method === 'DELETE') {
        // Extract the resource identifier from the URL
        const resourceId = req.url.slice(1); // Assuming the resource identifier is in the path

        // Check if the resource exists
        if (dataStore[resourceId]) {
            // Delete the resource from the data store
            delete dataStore[resourceId];

            // Respond with a success status
            res.writeHead(200, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ message: 'Resource deleted successfully!' }));
        }
        else {
            // If the resource is not found, respond with a 404 Not Found status
            res.writeHead(404, { 'Content-Type': 'text/plain' });
            res.end('Resource Not Found');
        }
    }
    else {
        // If the request method is not DELETE, respond with a 405 Method Not Allowed status
        res.writeHead(405, { 'Content-Type': 'text/plain' });
        res.end('Method Not Allowed!');
    }
});

server.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
});

6. PATCH

This HTTP method is used to apply partial modifications to a resource. The PATCH method is typically used for updating a resource with only the changes provided in the request.

Example

const http = require('http');
const PORT = 3000;

const myData = {
    // Initial data in the store
    user1: { name: 'John Doe', age: 30 },
    user2: { name: 'Jane Doe', age: 55 }
};

const server = http.createServer((req, res) => {
    if (req.method === 'PATCH') {
        let data = '';

        // Handle data chunks as they come in
        req.on('data', chunk => {
            data += chunk;
        });

        // When all data is received
        req.on('end', () => {
            // Extract the resource identifier from the URL
            const resourceId = req.url.slice(1); // Assuming the resource identifier is in the path

            // Check if the resource exists
            if (myData[resourceId]) {
                // Apply the patch to the resource in the data store
                const patchData = JSON.parse(data);
                Object.assign(myData[resourceId], patchData);

                // Respond with a success status
                res.writeHead(200, { 'Content-Type': 'application/json' });
                res.end(JSON.stringify({ message: 'Resource patched successfully!', data: myData[resourceId] }));
            }
            else {
                // If the resource is not found, respond with a 404 Not Found status
                res.writeHead(404, { 'Content-Type': 'text/plain' });
                res.end('Resource Not Found!');
            }
        });
    }
    else {
        // If the request method is not PATCH, respond with a 405 Method Not Allowed status
        res.writeHead(405, { 'Content-Type': 'text/plain' });
        res.end('Method Not Allowed!');
    }
});

server.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
});


7. OPTIONS

The OPTIONS method is used to describe the communication options for the target resource. It is often used to support CROS (Cross-Origin Resource Sharing) and other capabilities.

Example

const http = require('http');
const PORT = 5000;

const server = http.createServer((req, res) => {
    if (req.method === 'OPTIONS') {
        // Respond with headers describing allowed methods and headers
        res.writeHead(200, {
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
            'Access-Control-Allow-Headers': 'Content-Type',
        });
        res.end();
    }
    else {
        // Handle other types of requests
        res.writeHead(405, { 'Content-Type': 'text/plain' });
        res.end('Method Not Allowed!');
    }
});

server.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
});


8. TRACE

The TRACE HTTP Method is used to perform a message loop-back test along the path to the target resource. It helps in debugging and diagnostics but is often disabled for security reasons.

Example

const http = require('http');
const PORT = 5000;

const server = http.createServer((req, res) => {
    if (req.method === 'TRACE') {
        // Echo back the received request in the response body
        const requestBody = [];
        req.on('data', chunk => {
            requestBody.push(chunk);
        });

        req.on('end', () => {
            const originalRequest = Buffer.concat(requestBody).toString();
            res.writeHead(200, { 'Content-Type': 'message/http' });
            res.end(originalRequest);
        });
    }
    else {
        // Handle other types of requests
        res.writeHead(405, { 'Content-Type': 'text/plain' });
        res.end('Method Not Allowed!');
    }
});

server.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
});

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.

Top Post Ad

Below Post Ad