top of page

HTTP Module in Node.js

Writer's picture: Anushka ShrivastavaAnushka Shrivastava

Updated: Oct 5, 2022



HTTP module is a built-in core module in Node.js, which allows node.js to transfer data over Hyper Text Transfer Protocol (HTTP). HTTP is a protocol on the application layer of OSI Model.


To use the module in our code, we need to use require() method.


const http = require(‘http’);

The HTTP Module provides some properties, methods and class.




In this post, we will be discussing about the methods of HTTP module.


1. http.createServer() -


The createServer() method creates a server on our computer and turns our computer into an HTTP server.

It returns a new instance of the http.Server class. The http.Server object can listen to ports on our computer and execute a function, each time a request is made.


Syntax –


const server = http.createServer((req, res) => {
  // handle every single request with this callback
});
  


2. http.request() -


The request() method makes an http request to a server, which creates an instance of the http.ClientRequest class.


3. http.get() -


The get() method of HTTP module if similar to the request() method. But, http.get() method sets the HTTP method to GET and calls the req.end() automatically.


Let us try to understand the http module through an example code.



const http = require('http');

http.createServer(function (req, res) {
  res.write('Hello World!');
  res.end();
}).listen(3000);
  

On typing the following command in terminal -



node app.js

where, app.js is the name of the file, we get following as our output -




In the above code,


We import the http module in our code by using require() method.


const http = require('http');

Then, we create an object of the server to connect our computer to the server.


http.createServer(function (req, res) {
    // code 
)}
    

The write() method writes response to the client and end() method ends the response.



  res.write('Hello World!');
  res.end();
  


The listen() method specifies a PORT Number within itself. The server object then listens to the port number provided.


With this, we come to an end to HTTP Module in Node.js.


Thank you.

29 views0 comments

Recent Posts

See All

Hello World in Node.js

Node.js is an open source server environment that runs on various platforms such as Windows, Linux, Mac OS, etc. Node.js uses JavaScript...

Commentaires


Graphic Cubes

Subscribe To Get Latest Updates

Subscribe to our newsletter • Don’t miss out!

Thanks for subscribing!

Blogger
bottom of page