Ch-5 Web Server
Ch-5 Web Server
Web Server
Contents
• 5.1 Creating Web Server
• 5.2 Handling HTTP requests
• 5.3 Sending Requests
• 5.4 HTTP Streaming
What is web server?
• To access web pages of any web application, you need a web server.
• The web server will handle all the http requests for the web application.
• Web servers usually deliver html documents along with images, style sheets,
and scripts.
• Example IIS is a web server for ASP.NET web applications and Apache is a
web server for PHP or Java web applications.
• Node.js provides capabilities to create your own web server which will
handle HTTP requests asynchronously.
• You can use IIS or Apache to run Node.js web application but it is
recommended to use Node.js web server.
Web Application Architecture
• A Web application is usually divided into four layers −
1. The basic functionality of the require function is that it reads a JavaScript file,
executes the file, and then proceeds to return the exports object. So in our case,
since we want to use the functionality of the http module, we use the require
function to get the desired functions from the http module so that it can be used
in our application.
2. In this line of code, we are creating a server application which is based on a
simple function. This function is called whenever a request is made to our server
application.
3. When a request is received, we are saying to send a response with a header type
of '200.' This number is the normal response which is sent in an http header when
a successful response is sent to the client.
4. In the response itself, we are sending the string 'Hello World.'
5. We are then using the server.listen function to make our server application listen
to client requests on port no 7000. You can specify any available port over here.
Output
Handle HTTP Request
• The http.createServer() method includes request and response parameters
which is supplied by Node.js.
• The request object can be used to get information about the current HTTP
request e.g., url, request header, and data.
• The response object can be used to send a response for a current HTTP
request.
• In Node.js, write and writeHead are two methods provided by
the http.ServerResponse class, which is used to send a response back to the
client during an HTTP request.
1) writeHead:
The writeHead method is used to send the response header to the client. It takes
in three parameters: statusCode, statusMessage, and
an optional headers object.
Here's the breakdown:
Syntax:
response.writeHead(statusCode[, statusMessage][, headers])
• statusCode :
Parameters: This method accepts the following argument as a parameter.
• statusCode(required): It is the 3-digit HTTP status code.It represents the HTTP status
code of the response, indicating the outcome of the request (e.g., 200 for success,
404 for not found, etc.).
• statusMessage(optional): It is a human-readable status message. It is an optional
parameter. It allows you to provide a custom status message that corresponds to
the status code. If not provided, a default message
will be sent based on the status code.
• headers (optional): It is an object containing additional headers to be sent with the
response.
Return Value: This method has nothing to return.
Note that the write method does not end the response. You should follow it up
with either a call to end.
response.writeHead(200, { 'Content-Type': 'text/plain' });
response.write('Hello, World!');
response.end();
• The end method is used to finalize the response and send it back to the client.
After calling end, no further data can be written to the response.
• writeHead sets the response status code and headers, while write is used to send
the response body.
var http = require('http'); // Import Node.js core module
var server = http.createServer(function (req, res) { //create web server
if (req.url == '/') { //check the URL of the current request
res.writeHead(200, { 'Content-Type': 'text/html' });
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('Node.js web server at port 5000 is running..')
• In the previous example, req.url is used to check the url of the current
request and based on that it sends the response.
• To send a response, first it sets the response header using writeHead()
method and then writes a string as a response body using write() method.
• Finally, Node.js web server sends the response using end() method.
• Now, run the above web server as shown below.
C:\> node server.js
Node.js web server at port 5000 is running..
• Open Web browser and type http://localhost:5000 and see the
following result.
Open Web browser and type http://localhost:5000/student and see the
following result.
It will display "Invalid Request" for all requests other than the above
URLs.
Sending Request using Request Module
Making HTTP Requests
• The request module is used to make HTTP calls. It is the simplest way of making
HTTP calls in node.js using this request module.
• It follows redirects by default.
Note: As of Feb 11th, 2020, the request is fully deprecated.
Feature of Request module:
• It is easy to get started and easy to use.
• It is a widely used and popular module for making HTTP calls.
const request = require('request');
let options = {
url: 'http://localhost:8080/hello.json',
method: 'GET',
headers: {
'Accept': 'application/json',
'Accept-Charset': 'utf-8',
'User-Agent': 'localhost'
}
};
// Request URL
let url = 'https://jsonplaceholder.typicode.com/todos/1';
// Printing body
console.log(body);
});
Handle Post Request:
• Here we will learn how to handle HTTP POST request and get data
from the submitted form.
• Create index.html in your application and write following HTML code
in it.
<html>
<head>
<title>Calculator</title>
</head>
<body>
<h1>Simple Calculator.</h1>
<form action="/" method="post">
<input type="text" name="num1" placeholder="First Number">
<input type="text" name="num2" placeholder="Second Number">
<button type="submit" name="submit"> calculator </button>
</form>
</body>
</html>
Handle POST Route in Express.js:
const express = require("express");
const bodyParser = require("body-parser")
// New app using express module
const app = express();
app.use(bodyParser.urlencoded({
extended:true
}));
app.get("/", function(req, res) {
res.sendFile(__dirname + "/index.html");
});
app.post("/", function(req, res) {
var num1 = Number(req.body.num1);
var num2 = Number(req.body.num2);
var result = num1 + num2 ;
res.send("Addition - " + result);
});
app.listen(3000, function(){
console.log("server is running on port 3000");
})
• Steps To Run:
• npm install express
• npm install body-parser
• node app.js
• point your browser to http://localhost:3000
HTTP Streaming
• HTTP Streaming is a push-style data transfer technique that allows a web server to
continuously send data to a client over a single HTTP connection that remains open
indefinitely.
• In simple words using a stream, we can send the file contents to the user as it's
being loaded from disk, byte by byte.
• Since we don't have to wait for the entire file to load, this reduces the time taken by
the server to respond to the user's request.
• Streaming also reduces the memory usage required to handle the users' requests
since we don't need to load the entire file at once.
• Using HTTP streaming, the server is configured to hold the specified request from
the client and keep the response open.
• Keeping response open can push data.
Referance:- https://www.scaler.com/topics/nodejs/node-js-request/