Node.js Web Server



Node.js Web Server:

A software program that handles the HTTP requests sent by web applications, is called as Web Server. A web server responds with html documents or web pages to the HTTP clients.

Web Application Architecture:

 

LAYER DESCRIPTION
Client Layer Contains web and mobile applications that sent HTTP request to the web server.
Server Layer Contains Web server to intercept the requests sent by web applications and usually responds with html documents.
Business Layer Contains application server that interacts with the data layer and is also utilized for processing by server layer.
Data Layer Contains databases and other data sources.

To Create Node.js Web Server:

  • Import the http module using require() function.
  • Call the createServer() method with specified request and response parameter.
  • Call the listen() method with specified port number.
  • Type the command node server.js in command prompt.
  • Create the required html file in the same folder as server.js.
  • Open the link displayed in the command prompt message with the html filename added at the end of the link in any browser.

 

Example:
 //Server.js

 var http = require('http');

var fs = require('fs');

var url = require('url');

http.createServer( function (request, response)

{

var pathname = url.parse(request.url).pathname;

console.log("Request for " + pathname + " received.");

fs.readFile(pathname.substr(1), function (err, data)

{

if (err)

{

console.log(err);

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

}

else

{

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

response.write(data.toString());

}

response.end();

});

}).listen(8080);

console.log('Server running at http://127.0.0.1:8080/');

//Example.html

<html>

<head>

<title>Example</title>

</head>

<body>

Hello Tech Tutorialz!

</body>

</html>

 OUTPUT:

// At Command Prompt:

 Server running at http://127.0.0.1:8080/

Request for /example.html received.

// At Browser link —  http://127.0.0.1:8080/example.html:

 Hello Tech Tutorialz!

Tags: ,
Leave a comment

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

Subscribe now

Receive weekly newsletter with educational materials, new courses, most popular posts, popular books and much more!

https://bridgejunks.com/ https://crownmakesense.com/ https://brithaniabookjudges.com/ https://hughesroyality.com/ https://rhythmholic.com/ https://bandar89.simnasfikpunhas.com/ https://www.100calshop.co.il/products/thailand/ https://myasociados.com/ https://solyser.com/ http://konfidence.cz/ https://muscadinepdx.com/ https://bandar89.parajesandinos.com.ve/ https://goremekoop.com/ https://oncoswisscenter.com/ https://www.turunclifehotel.com/bandar89/ https://www.houseofproducts.biz/ https://taimoormphotography.com/
BIJI18 BIJI18 BIJI18