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

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


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

filter_none

edit
close

play_arrow

link
brightness_4
code

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();

chevron_right


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

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :

1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.