HTTP Module in Node Js

  • The HTTP module in Node.js provides functionality to create HTTP servers and clients. It is a core module that enables you to build web applications, APIs, and interact with other HTTP-based services. Here's an overview of the HTTP module along with examples:
Creating an HTTP Server:
  • To create an HTTP server, you use the `createServer` method provided by the HTTP module. This method takes a callback function as an argument, which will be invoked for each incoming HTTP request.


    const http = require('http');

    // Create an HTTP server
    const server = http.createServer((req, res) => {
        // Set the response header
        res.writeHead(200, { 'Content-Type': 'text/plain' });

        // Send the response body
        res.end('Hello, World!\n');
    });

    // Listen on port 3000
    const PORT = 3000;
    server.listen(PORT, () => {
        console.log(`Server running at http://localhost:${PORT}/`);
    });

  • In this example, a simple HTTP server is created that responds with "Hello, World!" for every incoming request. The server listens on port 3000.
Handling HTTP Requests:
  • The `createServer` callback function takes two parameters, `req` (request) and `res` (response). These objects represent the incoming request and the outgoing response, respectively.


    const http = require('http');

    const server = http.createServer((req, res) => {
        // Log the incoming request method and URL
        console.log(`Request Method: ${req.method}, URL: ${req.url}`);

        // Set the response header
        res.writeHead(200, { 'Content-Type': 'text/plain' });

        // Send the response body
        res.end('Hello, World!\n');
    });

    const PORT = 3000;
    server.listen(PORT, () => {
        console.log(`Server running at http://localhost:${PORT}/`);
    });

  • In this example, the server logs the request method and URL to the console.
Handling Different HTTP Methods and Routes:
  • You can use the `req.method` and `req.url` properties to determine the HTTP method and URL of the incoming request. This allows you to handle different routes or methods accordingly.

    const http = require('http');

    const server = http.createServer((req, res) => {
        // Log the incoming request method and URL
        console.log(`Request Method: ${req.method}, URL: ${req.url}`);

        // Set the response header
        res.writeHead(200, { 'Content-Type': 'text/plain' });

        // Handle different routes
        if (req.url === '/hello') {
            res.end('Hello, Route!\n');
        } else if (req.url === '/goodbye') {
            res.end('Goodbye, Route!\n');
        } else {
            res.end('Unknown Route!\n');
        }
    });

    const PORT = 3000;
    server.listen(PORT, () => {
        console.log(`Server running at http://localhost:${PORT}/`);
    });

  • In this example, the server responds differently based on the requested route (`/hello`, `/goodbye`, or an unknown route).
Making HTTP Requests (Client):
  • The HTTP module also provides functionality for making HTTP requests from a Node.js application. You can use the `http.request` method to initiate an HTTP request.

    const http = require('http');

    // Options for the HTTP request
    const options = {
        hostname: 'www.example.com',
        port: 80,
        path: '/path',
        method: 'GET',
    };

    // Make an HTTP request
    const req = http.request(options, (res) => {
        let data = '';

        // Receive data in chunks
        res.on('data', (chunk) => {
            data += chunk;
        });

        // Entire response received
        res.on('end', () => {
            console.log('Response:', data);
        });
    });

    // Handle errors
    req.on('error', (error) => {
        console.error('Error:', error.message);
    });

    // End the request
    req.end();

  • In this example, an HTTP GET request is made to `www.example.com/path`, and the response is logged to the console.
  • These examples demonstrate the basic usage of the HTTP module in Node.js for both creating HTTP servers and making HTTP requests. The HTTP module provides additional features and options, such as handling query parameters, parsing request bodies, and configuring HTTPS servers. Refer to the Node.js documentation for more in-depth information and details about the HTTP module: [Node.js HTTP Documentation](https://nodejs.org/api/http.html).

No comments:

Post a Comment