• Tutorials Logic, IN
  • +91 8092939553
  • info@tutorialslogic.com

HTTP Modules

HTTP Modules

NodeJS has a built-in module called HTTP, which allows NodeJS to transfer data over the Hyper Text Transfer Protocol (HTTP). Generally, NodeJS is used for developing server based applications, but using the HTTP module, you can easily create web servers that can respond to the client requests. To include the HTTP module, use the require() method:-

										    
											var http = require('http');
											
										

Using NodeJS as a Web Server

The HTTP module can create an HTTP server using createServer() method, which can listen to the server ports and gives a response back to the client.

										    
											var http = require('http');
											
											//Creating a server.
											http.createServer(function (request, response) {
											    response.write('Hello Tutorials Logic!'); //Write a response to the client
												response.end(); //End the response
											}).listen(8080); //The server listens on port 8080
											
										

When someone tries to access the computer on port 8080, the function passed into the http.createServer() method, will be executed and returns the response to the client.

Adding a HTTP Header

We should include HTTP header with correct content type. If the response from the HTTP server is supposed to be displayed as HTML, then you should include a HTTP header with content-type as text/html like below:-

										    
											var http = require('http');
											
											http.createServer(function (request, response) {
											    response.writeHead(200, {'Content-Type': 'text/html'});
												response.write('Hello Tutorials Logic!');
												response.end();
											}).listen(8080);
											
										

Reading the Query String

The method passed into the http.createServer() has a request argument which represents the request from the client, as an object and this object has a property called "url" which holds the part of the url that comes after the domain name.

										    
											var http = require('http');
											
											http.createServer(function (request, response) {
											    response.writeHead(200, {'Content-Type': 'text/html'});
												response.write(request.url);
												response.end();
											}).listen(8080);