Node JS HTTP server example


Node JS HTTP server example

Hi friends, in this tutorial, you will learn how to create a Node JS HTTP server. Before getting started with the HTTP server creation, you must know that HTTP is a built-in module in node js, and a module in node js acts like a javascript function or library. By using this HTTP module, we can transfer the data over the web browser.

To include a module in node js, we can do so with the help of require() as shown below

var http = require('http');

whereas

  • http inside require is the name of the module and
  • http with var is the object reference variable which will be used later to create the server object or any other object etc.

Create a node js HTTP server object

When you create a node js HTTP server object then the node js file acts like a web server and listens to the server port such as 8080 for localhost etc and gives the response to the browser or client.

Below is an example:- (test.js)

var http = require('http');

http.createServer(function (req, res) {
   res.writeHead(200, {'Content-Type': 'text/html'});
   res.end('Hi this is my first program in node js');
 }).listen(8080);

Explanation of the above code:-

On the above code, you have noticed that the function inside the createServer() is added with port listen(8080) that means if you type http://locahost:8080 in your browser then the browser will return the function executed written inside the createServer(). Save the above javascript code with the .js extension.

Also read, Text slideshow HTML with images using w3 CSS and javascript

Run the node js file using the terminal

  • open the command terminal of your computer and go to the path or location where the javascript file is stored.
  • write node filname.js and press enter.
  • Now, open the browser and hit the URL http://localhost:8080
  • Now the file will be executed and the result will be displayed to the browser.

Conclusion:- I hope this tutorial will help you to understand the concept. If there is any doubt then please leave a comment below. If you want to download Node JS then Click Here


Leave a Comment