Skip to content
Related Articles

Related Articles

Improve Article

Node.js | HTTP Module

  • Difficulty Level : Basic
  • Last Updated : 12 Jun, 2020

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 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:

var http = require('http');

We can create a HTTP server with the help of http.createServer() method.

Example 1:
Filename: max.js




var 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:
f
d

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

Syntax:

http.request(options[, callback])

Example 2:
Filename: max.js




var http = require('http');
  
var 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