Skip to content
Related Articles
Get the best out of our app
GeeksforGeeks App
Open App
geeksforgeeks
Browser
Continue

Related Articles

Node.js HTTP Module

Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article

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 

javascript




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

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

node max.js

Output:

Console Output:

 f

Browser Output:

 d

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 

javascript




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:

 d


My Personal Notes arrow_drop_up
Last Updated : 04 Apr, 2023
Like Article
Save Article
Similar Reads
Related Tutorials