Menu BAR

FEEL FREE TO ASK ANY PROGRAM and please mention any error if you find it

5 Feb 2024

NODE JS BUILT IN MODULE - HTTP


1) Creating an HTTP Server


1) We need to first import the 'http' module using the require function
                            var http = require ('http');

2) We will use the method createServer() to create an HTTP server:
                            http.createServer(function (req, res){
                            ... // your code here
                            }).listen(PORT_NUMBER); 

Example: 
// Import the built-in 'http' module 
const http = require('http'); 

// Define the hostname and port number 
const hostname = '127.0.0.1'; 
const port = 3000; 

// Create an HTTP server 
const server = http.createServer((req, res) => { 

        // Set the HTTP status code and content type in the response header 
        res.writeHead(200, {'Content-Type': 'text/plain'}); 

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

        }); 
        
// Start the server and listen on the specified port and hostname 
server.listen(port, hostname, () => { 
       console.log(`Server running at http://${hostname}:${port}/`); 
});


2) GET REQUEST to query



1) We will be using http.request() method to send an HTTP GET request to a server and handle the response.

2) Similarly, we will be importing the module using- 
                            var http = require ('http');

3) We will be defining the options for the HTTP request where we will be mentioning the hostname, port number, path (if any), and the method.
                            const options = {
                            hostname: 'jsonplaceholder.typicode.com',
                            port: 80,
                            path: '/posts',
                            method: 'GET'
                            }

4) Creating a http.request() method in which we are going to pass the above options object.

5) Store the response and display it or process it when the response is complete.

Example: 

// Import the built-in 'http' module 
const http = require('http'); 

// Define the options for the HTTP request 
const options = { 
        hostname: 'jsonplaceholder.typicode.com', 
        port: 80, 
        path: '/posts', 
        method: 'GET'
};

// Create the HTTP request 
const req = http.request(options, (res) => { 

        // Initialize a variable to store the response data 
        let data = ''; 

        // Concatenate chunks of data as they are received 
        res.on('data', (chunk) => { 
                data += chunk; 
        });
 
        // When the response is complete, log the data to the console 
        res.on('end', () => { 
            console.log(data); 
        }); 
}); 

// Handle errors that occur during the request 
req.on('error', (error) => { 
        console.error('An error occurred:', error); 
}); 

// End the request 
req.end(); 


No comments:

Post a Comment