Create server using NodeJS for web based app

In last tutorial, we have seen how to print 'hello mars' example, now lets create a server in nodejs. Server is required for web applications to run.

So this example will show to create server in your system, this example can also be found in https://nodejs.org/en/about/


// filename : local-server.js
const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Now in command prompt run the node local-server.js local-server-nodejs Now open the local host with port which we have mentioned in the program to view the app on browser http://127.0.0.1:3000/ local-server-app

  • Node provide us with the inbuilt http module which we can use to create the server, import the module by using require
  • We can create a server using the createServer() function, createServer() function takes a callback function as arguments. This callback is executed each time a request is received.
  • The two arguments of createServer() function are request and response
  • request : request contains all the information related to client's request such as URL, custom headers, client info, and more
  • response : response is used to return the data back to the client.
  • console.log() prints the given value or text to the terminal
  • response.end() is an inbuilt function which is used to tell the server that the request has been fulfilled.
  • server.listen() is an inbuilt method used to bind to the port an start listening for incoming connections.

About Author

Myself KarthiQ, I am the author of this blog, I know ways to write a good article but some how I donot have the skills to make it to reach people, would you like help me to reach more people By sharing this Article in the social media.

Share this Article Facebook
Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions

Recent Addition

new tutorial Selenium Online Training : Our next online training course for Selenium with Java starts from 17th December 2018.

You can attend first 3 classes for free, the total course fee is INR 10,000

The course time would be 8.00 PM(IST) for the first three classes

If you are interested to learn, then you can join the course by sending email to chercher.tech@gmail.com

or Register below


 
Join My Facebook Group
Join Group