Open In App

Node.js HTTP Module

To make HTTP requests in Node.js, there is a built-in module HTTP in Node.js to transfer data over the HTTP. To use the HTTP server in the node, we need to require the HTTP module. The HTTP module creates an HTTP server that listens to server ports and gives a response back to the client.

Syntax:



const http = require('http');

Example 1: In this example, we can create an HTTP server with the help of http.createServer() method. 

Filename: max.js 






const http = require('http');
 
// Create a server
http.createServer((request, response) => {
 
    // Sends a chunk of the response body
    response.write('Hello World!');
 
    // Signals the server that all of
    // the response headers and body
    // have been sent
    response.end();
}).listen(3000); // Server listening on port 3000
 
console.log("Server started on port 3000");

Step to run this program: Run this max.js file using the below command:

node max.js

Output:

Console Output:

 

Browser Output:

 

To make requests via the HTTP module http.request() method is used. 

Syntax:

http.request(options[, callback])

Example 2: In this example, we will see to make requests via the HTTP module http.request() method. 

Filename: max.js 




const http = require('http');
 
let options = {
    host: 'www.geeksforgeeks.org',
    path: '/courses',
    method: 'GET'
};
 
// Making a get request to
// 'www.geeksforgeeks.org'
http.request(options, (response) => {
 
    // Printing the statusCode
    console.log(`STATUS: ${response.statusCode}`);
}).end();

Step to run this program: Run this max.js file using the below command:

node max.js

Output:

 


Article Tags :