SlideShare uma empresa Scribd logo
1 de 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);

Mais conteúdo relacionado

Semelhante a Web Server.pdf

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...WebStackAcademy
 
Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Asynchronous JavaScript & XML (AJAX)
Asynchronous JavaScript & XML (AJAX)Adnan Sohail
 
Ruby HTTP clients comparison
Ruby HTTP clients comparisonRuby HTTP clients comparison
Ruby HTTP clients comparisonHiroshi Nakamura
 
Java web programming
Java web programmingJava web programming
Java web programmingChing Yi Chan
 
Http programming in play
Http programming in playHttp programming in play
Http programming in playKnoldus Inc.
 
Unit-5.pptx
Unit-5.pptxUnit-5.pptx
Unit-5.pptxitzkuu01
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
13 networking, mobile services, and authentication
13   networking, mobile services, and authentication13   networking, mobile services, and authentication
13 networking, mobile services, and authenticationWindowsPhoneRocks
 
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.pdfAssignmenVannaSchrader3
 
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.docxalfredacavx97
 
Node.js introduction
Node.js introductionNode.js introduction
Node.js introductionParth Joshi
 
Rpi python web
Rpi python webRpi python web
Rpi python websewoo lee
 

Semelhante a 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
 

Mais de Bareen Shaikh

Express Generator.pdf
Express Generator.pdfExpress Generator.pdf
Express Generator.pdfBareen Shaikh
 
ExpressJS-Introduction.pdf
ExpressJS-Introduction.pdfExpressJS-Introduction.pdf
ExpressJS-Introduction.pdfBareen Shaikh
 
Express JS-Routingmethod.pdf
Express JS-Routingmethod.pdfExpress JS-Routingmethod.pdf
Express JS-Routingmethod.pdfBareen Shaikh
 
FS_module_functions.pptx
FS_module_functions.pptxFS_module_functions.pptx
FS_module_functions.pptxBareen Shaikh
 
Introduction to Node JS1.pdf
Introduction to Node JS1.pdfIntroduction to Node JS1.pdf
Introduction to Node JS1.pdfBareen Shaikh
 
Introduction to Node JS.pdf
Introduction to Node JS.pdfIntroduction to Node JS.pdf
Introduction to Node JS.pdfBareen Shaikh
 

Mais 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
 

Último

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...Miguel Araújo
 
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 2024The Digital Insurer
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
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 DevelopmentsTrustArc
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 

Último (20)

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...
 
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
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
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
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 

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);