How To Build A Nodejs Web Server Application In A Few Steps?

By Padma Priya | Posted on February 6, 2020

Learn how to build a Nodejs web server application in a few steps with HTTP requests in this blog.

A Web Server is a software application that handles HTTP requests sent by the HTTP client, such as web browsers, and in turn, it produces the web page for the client. Each web server delivers HTML documents along with images, sheets, and scripts.

Build an ecommerce platform with Nodejs for fuller business performance!

Most of the web servers support server-side scripts. It uses scripting languages that assign a task to an application server to retrieve data from a database. These servers perform some complex logic and then send a response to the HTTP client through the web server.

Read More: How To Install Node Version Manager NVM?

Are You Prepared to Switch to a Headless Solution? Explore the benefits of Webnexs' headless solution, which provides unparalleled speed and flexibility to your business. Request Demo

What Is Nodejs Server?

Node js is a web server widely used to create server-side applications. This framework enables the creation of a web server that delivers web content to the users by requesting the web server.

What Is Nodejs Web Server

There are a variety of modules available in Nodejs such as the “HTTP” and “request” modules. These modules help in processing server-related requests in allocated web server space. In this blog, let’s see how to create a basic web server application using Nodejs.

Read More: 5 ways to make HTTP requests in Nodejs

Web Application Architecture

A web application architecture is broadly classified into 4 layers:

  • Client Layer – The Client layer includes web browsers and mobile applications that make HTTP requests to the web server.
  • Server Layer – The Server layer consists of a web server that can intercept the request made by clients and pass the immediate response.
  • Business Layer – The business layer communicates with the data layer through a database. It contains an application server utilized by the web server to process the requests. 
  • Data Layer – This layer acts as the source of data or the database.

Read More: The perfect architecture of Nodejs: How it works technically?

Create a Nodejs Web Server

To create a web server using Nodejs, processes the incoming requests asynchronously,

The following example is to create a Nodejs web server contained in server.js file in its directory:

var http = require('http'); // 1 - Import Nodejs core module 

var server = http.createServer(function (req, res) { // 2 -creating server 

   //handle incomming requests here.. 

}); server.listen(5000); //3 - listen for any incoming requests 

console.log('Nodejs web server at port 5000')

Import the HTTP module using require() function in the above example. This HTTP  module is considered to be a core module of Nodejs. So the need to install it using Node Package Manager.

Taking the further step to call createServer() method of HTTP and specify the Nodejs callback function with the request that arrived from the client

In the end, call listen()method of server object which was returned from createServer() method with a port number.

Now run the above web server by writing node server.js command in command prompt and it will display a message as shown below.

C: \> node server.js

Nodejs web server at port 5000 is running

This is how you create a Nodejs web server using a programming method. Now, the following steps help you to handle HTTP requests and send the response to the Nodejs web server.

Read More: Understanding Event Emitter In Nodejs

Handle HTTP Request In Node Web Server

The http.createServer() method includes both the request and response parameters generated by Nodejs. To get information about the current HTTP request, use the request object.

Such HTTP information contains url, request header, and data. The following example illustrates handling HTTP requests and responses in Nodejs web server.

var http = require('http'); // Import Nodejs core module 

var server = http.createServer(function (req, res) { // create web server 

   if (req.url == '/') { // check the URL of the current request 

// set response header

 res.writeHead(200, { 'Content-Type': 'text/html' }); 

/ set response content 

res.write('<html><body><p>This is home Page.</p></body></html>'); res.end();

}

else if (req.url == "/student") {

res.writeHead(200, { 'Content-Type': 'text/html' }); 

res.write('<html><body><p>This is student Page.</p></body></html>'); 

res.end();



else if (req.url == "/admin") {

res.writeHead(200, { 'Content-Type': 'text/html' }); 

res.write('<html><body><p>This is admin Page.</p></body></html>'); 

res.end(); 



else res.end('Invalid Request!'); }); 

server.listen(5000); //6 - listen for any incoming requests 

console.log('Nodejs web server at port 5000')

From the above scenario, req.url is used to check the url of the current request.and sends the response. 

To send a response, set the response header using writeHead() method and then write a string as a response body using write() method. 

Finally, the Nodejs web server sends the response using end() method as requested by the client.

Now just run the above web server as shown below:

C: \> node server.js

Nodejs web server at port 5000

To test the sample code, use the command-line program curl, a preinstalled program that comes with most  Mac and Linux machines.

Curl  -i http://localhost:5000

After the completion of the above steps, now you can actually see the following response:

HTTP/1.1 200 OK

Content-Type: text/plain

Date: Wed, 22 Jan 05:36:05 GMT

Connection: keep-alive

This is home page

For Windows users, use http://localhost:5000 in your browser and see the following result.

http://localhost:5000

This is Home page

In the same way, use  http://localhost:5000/student in your browser and see the following result.

http://localhost:5000/student

This is student page

It shows “Invalid Request” for all other requests other than the above URLs.

Send JSON Response

The following example illustrates how to serve JSON response from the Nodejs web server.

var http = require('http');

var server = http.createServer(function (req, res) { 

if (req.url == '/data') 
{ //check the URL of the current request          res.writeHead(200, 

{ 'Content-Type': 'application/json' }); res.write(JSON.stringify({ message: "Hello World"}));

res.end();

}

}); 

server.listen(5000); 

console.log('Nodejs web server at port 5000')

In this simple way, you can create a Nodejs web server that servers with different responses for different functions.

Read More: Golang vs Nodejs: Which Suits Best For Backend Development?

Web Server Nodejs Conclusion

In Nodejs, we have used http.createServer() method of HTTP Built-in Nodejs module to create an HTTP Web Server that responds to the requests made at a port.

Read More: Top 10 Useful Nodejs Packages For Web Development

If you’re planning to build a Nodejs web application, We happily build it for you. Contact us for more details regarding web development.

Launching Headless Ecommerce in Node.js, Powered by Microservices. Click Here to Inquire for Your Business.

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *