How to build a Nodejs web server in a few steps?

Learn how to build a Nodejs web server 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 to the client. Each Web server delivers HTML documents along with images, sheets, and scripts.

Build an e-commerce 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 sends a response to the HTTP client through the Web server.

Nodejs web server

Nodejs framework is widely used to create server-side applications. This framework enables creating a web server that delivers web content to the users by requesting the web server.

Build a nodejs web server

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

Read: 5 ways to make HTTP requests in Nodejs

Web application architecture

A web application architecture broadly classified into 4 layers:

  • Client Layer – The Client layer includes web browsers, 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 web server to process the requests. 
  • Data Layer: This layer acts as the source of data or the database.

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

Create a Nodejs web server:

To create a web server using Nodejs, it 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 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 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 in the Nodejs web server.

Handle HTTP request

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 from 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 could 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.

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.

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

Comments

Leave a Reply

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