SlideShare une entreprise Scribd logo
1  sur  20
WEB SERVER
Prepared By: Bareen Shaikh
Topics
5.1 Creating Web Server
5.2 Handling HTTP requests
5.3 Sending Requests
5.4 HTTP Streaming
Introduction
 Web Application needs Web Server.
 Communication between Client & Server using HTTP.
 IIS web server for ASP.NET web application.
 Apache web server for PHP and Java web application.
 Create Node.Js web server for Node.js application.
Creating Node.Js web server
 Node.js makes create a simple web server that processes
incoming requests asynchronously.
 Following example is a simple Nodejs web server example
var http = require('http'); // http Node.js core module
var server = http.createServer(function (req, res) {
//handle request
}); server.listen(8080); //listen for any incoming requests
console.log('Node.js web server at port 8080 is running..')
Creating Node.Js web server
In the above example,
 http core module is imported using require() function.
 As http module is a core module of Node.js, no need to install it
using NPM.
 Next step is call createServer() method of http
 In that specify callback function with request and response
parameter.
 Finally, call listen() method of server object.
 Which start listening to incoming requests on port 8080.
 Can specify any unused port here.
createServer()
const http = require('http');
const server = http.createServer((request, response) => {
// Task to be done!
});
OR
const http = require('http');
const server = http.createServer();
server.on('request', (request, response) => {
// Task to be done
});
CreateServer() Explanation
 The function that's passed in to createServer is called once
for every HTTP request.
 It works as a request handler.
 The server object returned by createServer is an EventEmitter.
 HTTP request hits the server, node calls the request handler
function for dealing with the transaction,request and response
Simple Hello World Example
var http = require('http');
//create a server object:
var server=http.createServer(function (req, res) {
res.write('Hello World!'); //write a response to the client
res.end(); //end the response
});server.listen(8080); //the server object listens on port
8080
HTTP Request and Response
 The http.createServer() method
includes request and response parameters
 The request object can be used to get information about
the current HTTP request e.g.,methods, url, request header,
and data.
 The response object can be used to send a response for a
current HTTP request.
Handling http request
 The first thing while handling request is to check method
and URL, so that appropriate actions can be taken.
 Node.js makes this relatively painless by putting handy
properties onto the request object as follows
const { method, url ,header} = request;
 Parameter:
method here will GET/POST/PUT normal HTTP
method/verb.
url is the full URL without the server, protocol or port.
Request Body
let body = [];
request.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
// body has the entire request body, stored in it as
a string
});
Request Body explanation
 request object passed in to a handler implements
the ReadableStream interface.
 This stream can be listened or piped.
 Data can be read out of the stream by listening to the
stream's 'data' and 'end' events.
 The chunk emitted in each 'data' event is a Buffer.
 Most probably data going to be string data, the best is
to collect the data in an array,
 At the 'end', concatenate and stringify it.
Error handling while http request
request.on('error', (err) => {
// This prints the error message and stack trace to `stderr`.
console.error(err.stack);
});
 The request object is a ReadableStream, which is
an EventEmitter
 An error in the request stream presents itself by emitting
an 'error' event.
 If event listener is not handle in program then the error will
be thrown.
Overall Program of HTTP request
const http = require('http');
http.createServer((request, response) =>
{
const { headers, method, url } = request;
let body = []; request.on('error', (err) =>
{
console.error(err);
}).on('data', (chunk) => {
body.push(chunk); }).on('end', () => {
body = Buffer.concat(body).toString();
});
}).listen(8080);
HTTP Response
 response object is an instance of ServerResponse which is
a WritableStream.
 It contains many methods for sending data back to the
client.
 HTTP Status code
 HTTP status code on a response always be 200.
 Not every HTTP response warrants this such as
response.statusCode = 404; // Tell the client that the resource
wasn't found.
Setting Response Headers
 Headers are set through a convenient method
called setHeader()
 response.setHeader('Content-Type', ‘text/html');
 Explicitly Sending Header Data with method
called writeHead() which writes the status code and the
headers to the stream.
 response.writeHead(200, { 'Content-Type': ‘text/html’});
Sending Response Body
 response object is a WritableStream writing a response
body out to the client.
 response.write() method is used to write streams.
response.write('<html>');
response.write('<body>');
response.write('<h1>Hello, World!</h1>');
response.write('</body>');
response.write('</html>');
response.end()
OR
response.end('<html><body><h1>Hello,
World!</h1></body></html>');
Error handling while http response
response.on('error', (err) => {
// This prints the error message and stack trace to `stderr`.
console.error(err.stack);
});
 The response object is a WritableStream, which is
an EventEmitter.
 An error in the response stream presents itself by emitting
an 'error' event.
 If event listener is not handle in program then the error will
be thrown.
Put overall code together of http request
and response
Simplified overall program
const http = require('http');
http.createServer((request, response) => {
let body = [];
request.on('data', (chunk) => {
body.push(chunk);
}).on('end', () => {
body = Buffer.concat(body).toString();
response.end(body);
});
}).listen(8080);

Contenu connexe

Similaire à Web Server.pdf

Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
Hiroshi Nakamura
 
Java web programming
Java web programmingJava web programming
Java web programming
Ching Yi Chan
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
VannaSchrader3
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
alfredacavx97
 

Similaire à Web Server.pdf (20)

Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparison
 
Basics Of Servlet
Basics Of ServletBasics Of Servlet
Basics Of Servlet
 
Java web programming
Java web programmingJava web programming
Java web programming
 
Http programming in play
Http programming in playHttp programming in play
Http programming in play
 
AJAX
AJAXAJAX
AJAX
 
AJAX
AJAXAJAX
AJAX
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
 
Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptx
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
Ajax
AjaxAjax
Ajax
 
Servlets
ServletsServlets
Servlets
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
13 networking, mobile services, and authentication
13   networking, mobile services, and authentication13   networking, mobile services, and authentication
13 networking, mobile services, and authentication
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmenMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen
 
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docxMCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
MCIS 6163 Assignment 1MCIS 6163 Assignment 1.pdfAssignmen.docx
 
08 ajax
08 ajax08 ajax
08 ajax
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introduction
 
Rpi python web
Rpi python webRpi python web
Rpi python web
 

Plus de Bareen Shaikh (11)

Express Generator.pdf
Express Generator.pdfExpress Generator.pdf
Express Generator.pdf
 
Middleware.pdf
Middleware.pdfMiddleware.pdf
Middleware.pdf
 
ExpressJS-Introduction.pdf
ExpressJS-Introduction.pdfExpressJS-Introduction.pdf
ExpressJS-Introduction.pdf
 
Express JS-Routingmethod.pdf
Express JS-Routingmethod.pdfExpress JS-Routingmethod.pdf
Express JS-Routingmethod.pdf
 
FS_module_functions.pptx
FS_module_functions.pptxFS_module_functions.pptx
FS_module_functions.pptx
 
File System.pptx
File System.pptxFile System.pptx
File System.pptx
 
NPM.pdf
NPM.pdfNPM.pdf
NPM.pdf
 
NodeJs Modules1.pdf
NodeJs Modules1.pdfNodeJs Modules1.pdf
NodeJs Modules1.pdf
 
NodeJs Modules.pdf
NodeJs Modules.pdfNodeJs Modules.pdf
NodeJs Modules.pdf
 
Introduction to Node JS1.pdf
Introduction to Node JS1.pdfIntroduction to Node JS1.pdf
Introduction to Node JS1.pdf
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdf
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Developing An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of BrazilDeveloping An App To Navigate The Roads of Brazil
Developing An App To Navigate The Roads of Brazil
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, AdobeApidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
Apidays New York 2024 - Scaling API-first by Ian Reasor and Radu Cotescu, Adobe
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 

Web Server.pdf

  • 1. WEB SERVER Prepared By: Bareen Shaikh
  • 2. Topics 5.1 Creating Web Server 5.2 Handling HTTP requests 5.3 Sending Requests 5.4 HTTP Streaming
  • 3. Introduction  Web Application needs Web Server.  Communication between Client & Server using HTTP.  IIS web server for ASP.NET web application.  Apache web server for PHP and Java web application.  Create Node.Js web server for Node.js application.
  • 4. Creating Node.Js web server  Node.js makes create a simple web server that processes incoming requests asynchronously.  Following example is a simple Nodejs web server example var http = require('http'); // http Node.js core module var server = http.createServer(function (req, res) { //handle request }); server.listen(8080); //listen for any incoming requests console.log('Node.js web server at port 8080 is running..')
  • 5. Creating Node.Js web server In the above example,  http core module is imported using require() function.  As http module is a core module of Node.js, no need to install it using NPM.  Next step is call createServer() method of http  In that specify callback function with request and response parameter.  Finally, call listen() method of server object.  Which start listening to incoming requests on port 8080.  Can specify any unused port here.
  • 6. createServer() const http = require('http'); const server = http.createServer((request, response) => { // Task to be done! }); OR const http = require('http'); const server = http.createServer(); server.on('request', (request, response) => { // Task to be done });
  • 7. CreateServer() Explanation  The function that's passed in to createServer is called once for every HTTP request.  It works as a request handler.  The server object returned by createServer is an EventEmitter.  HTTP request hits the server, node calls the request handler function for dealing with the transaction,request and response
  • 8. Simple Hello World Example var http = require('http'); //create a server object: var server=http.createServer(function (req, res) { res.write('Hello World!'); //write a response to the client res.end(); //end the response });server.listen(8080); //the server object listens on port 8080
  • 9. HTTP Request and Response  The http.createServer() method includes request and response parameters  The request object can be used to get information about the current HTTP request e.g.,methods, url, request header, and data.  The response object can be used to send a response for a current HTTP request.
  • 10. Handling http request  The first thing while handling request is to check method and URL, so that appropriate actions can be taken.  Node.js makes this relatively painless by putting handy properties onto the request object as follows const { method, url ,header} = request;  Parameter: method here will GET/POST/PUT normal HTTP method/verb. url is the full URL without the server, protocol or port.
  • 11. Request Body let body = []; request.on('data', (chunk) => { body.push(chunk); }).on('end', () => { body = Buffer.concat(body).toString(); // body has the entire request body, stored in it as a string });
  • 12. Request Body explanation  request object passed in to a handler implements the ReadableStream interface.  This stream can be listened or piped.  Data can be read out of the stream by listening to the stream's 'data' and 'end' events.  The chunk emitted in each 'data' event is a Buffer.  Most probably data going to be string data, the best is to collect the data in an array,  At the 'end', concatenate and stringify it.
  • 13. Error handling while http request request.on('error', (err) => { // This prints the error message and stack trace to `stderr`. console.error(err.stack); });  The request object is a ReadableStream, which is an EventEmitter  An error in the request stream presents itself by emitting an 'error' event.  If event listener is not handle in program then the error will be thrown.
  • 14. Overall Program of HTTP request const http = require('http'); http.createServer((request, response) => { const { headers, method, url } = request; let body = []; request.on('error', (err) => { console.error(err); }).on('data', (chunk) => { body.push(chunk); }).on('end', () => { body = Buffer.concat(body).toString(); }); }).listen(8080);
  • 15. HTTP Response  response object is an instance of ServerResponse which is a WritableStream.  It contains many methods for sending data back to the client.  HTTP Status code  HTTP status code on a response always be 200.  Not every HTTP response warrants this such as response.statusCode = 404; // Tell the client that the resource wasn't found.
  • 16. Setting Response Headers  Headers are set through a convenient method called setHeader()  response.setHeader('Content-Type', ‘text/html');  Explicitly Sending Header Data with method called writeHead() which writes the status code and the headers to the stream.  response.writeHead(200, { 'Content-Type': ‘text/html’});
  • 17. Sending Response Body  response object is a WritableStream writing a response body out to the client.  response.write() method is used to write streams. response.write('<html>'); response.write('<body>'); response.write('<h1>Hello, World!</h1>'); response.write('</body>'); response.write('</html>'); response.end() OR response.end('<html><body><h1>Hello, World!</h1></body></html>');
  • 18. Error handling while http response response.on('error', (err) => { // This prints the error message and stack trace to `stderr`. console.error(err.stack); });  The response object is a WritableStream, which is an EventEmitter.  An error in the response stream presents itself by emitting an 'error' event.  If event listener is not handle in program then the error will be thrown.
  • 19. Put overall code together of http request and response
  • 20. Simplified overall program const http = require('http'); http.createServer((request, response) => { let body = []; request.on('data', (chunk) => { body.push(chunk); }).on('end', () => { body = Buffer.concat(body).toString(); response.end(body); }); }).listen(8080);