SlideShare a Scribd company logo
1 of 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);

More Related Content

Similar to 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
 

Similar to 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
 

More from 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
 

More from 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
 

Recently uploaded

9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding TeamAdam Moalla
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8DianaGray10
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPathCommunity
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Will Schroeder
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IES VE
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfDaniel Santiago Silva Capera
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopBachir Benyammi
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarPrecisely
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6DianaGray10
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxUdaiappa Ramachandran
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7DianaGray10
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?IES VE
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdfPedro Manuel
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Commit University
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostMatt Ray
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UbiTrack UK
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-pyJamie (Taka) Wang
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxGDSC PJATK
 

Recently uploaded (20)

9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team9 Steps For Building Winning Founding Team
9 Steps For Building Winning Founding Team
 
UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8UiPath Studio Web workshop series - Day 8
UiPath Studio Web workshop series - Day 8
 
UiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation DevelopersUiPath Community: AI for UiPath Automation Developers
UiPath Community: AI for UiPath Automation Developers
 
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
Apres-Cyber - The Data Dilemma: Bridging Offensive Operations and Machine Lea...
 
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
IESVE Software for Florida Code Compliance Using ASHRAE 90.1-2019
 
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdfIaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
IaC & GitOps in a Nutshell - a FridayInANuthshell Episode.pdf
 
NIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 WorkshopNIST Cybersecurity Framework (CSF) 2.0 Workshop
NIST Cybersecurity Framework (CSF) 2.0 Workshop
 
AI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity WebinarAI You Can Trust - Ensuring Success with Data Integrity Webinar
AI You Can Trust - Ensuring Success with Data Integrity Webinar
 
UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6UiPath Studio Web workshop series - Day 6
UiPath Studio Web workshop series - Day 6
 
Building AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptxBuilding AI-Driven Apps Using Semantic Kernel.pptx
Building AI-Driven Apps Using Semantic Kernel.pptx
 
UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7UiPath Studio Web workshop series - Day 7
UiPath Studio Web workshop series - Day 7
 
How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?How Accurate are Carbon Emissions Projections?
How Accurate are Carbon Emissions Projections?
 
Nanopower In Semiconductor Industry.pdf
Nanopower  In Semiconductor Industry.pdfNanopower  In Semiconductor Industry.pdf
Nanopower In Semiconductor Industry.pdf
 
20150722 - AGV
20150722 - AGV20150722 - AGV
20150722 - AGV
 
Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)Crea il tuo assistente AI con lo Stregatto (open source python framework)
Crea il tuo assistente AI con lo Stregatto (open source python framework)
 
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCostKubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
KubeConEU24-Monitoring Kubernetes and Cloud Spend with OpenCost
 
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
UWB Technology for Enhanced Indoor and Outdoor Positioning in Physiological M...
 
20230202 - Introduction to tis-py
20230202 - Introduction to tis-py20230202 - Introduction to tis-py
20230202 - Introduction to tis-py
 
201610817 - edge part1
201610817 - edge part1201610817 - edge part1
201610817 - edge part1
 
Cybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.pptxCybersecurity Workshop #1.pptx
Cybersecurity Workshop #1.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);