KEMBAR78
httpmodule in java script all methods.pptx
http module
• the http module is pretty low level
• it is not difficult to implement a full webserver using just the http
module.
• It doesn’t provide calls to handle routing, cookies.
• using the http module for is implementing backend web services for your
applications to use.(That is where the http module becomes an
invaluable tool in your arsenal.)
• You can create basic HTTP servers that provide
• an interface for communications behind your firewall and then basic
HTTP clients that interact with those services.
• Note:When you get to the Express, you will see the advantages it
provides. caching, and so on
• var url = require('url');
• var urlStr =
'http://user:pass@host.com:80/resource/path
?query=string#hash
• var urlObj = url.parse(urlStr, true, false);
• urlString = url.format(urlObj);
Processing Query Strings and Form
Parameters
• HTTP requests often include query strings in
the URL or parameter data in the body for
form submissions.
• The query string can be obtained from the
URL object defined in the previous section.
The parameter data sent by a form request
can be read out of the body of the client
request.
• The query string and form parameters are just
basic key-value pairs.
• To actually consume these values in your
Node.js webserver you need to convert the
string into a JavaScript object using the parse()
method from the querystring module:
querystring.parse(str, [sep], [eq], [options])
• The str parameter is the query or parameter string.
• The sep parameter allows you to specify the
separator character used. The default separator
character is &.
• The eq parameter allows you to specify the
assignment character to use when parsing.
• The default is =. The options parameter is an object
with the property maxKeys that allows you to limit
the number of keys the resulting object can contain.
• The default is 1000. If you specify 0, there is no
limit.
• The following shows an example of using
parse() to parse a query string:
• var qstring = require('querystring');
• var params =
qstring.parse("name=Brad&color=red&color=
blue");
• The params object created would be:
{name: 'Brad', color: ['red', 'blue']}
Understanding Request, Response, and
Server Objects
• To use the http module in Node.js applications, you
first need to understand the request and response
objects.
• They provide the information and much of the
functionality that comes into and out of the HTTP
clients and servers.
• Once you see the makeup of these objects—
including properties, events, and methods they
provide—it will be simple to implement your own
HTTP servers and clients.
• The following sections cover the purpose and
behavior of the ClientRequest,
ServerResponse, IncomingMessage, and
Server objects.
The http.ClientRequest Object
• The ClientRequest object is created internally when
you call http.request() when building the HTTP client.
• This object represents the request while it is in
progress to the server. You use the ClientRequest
object to initiate, monitor, and handle the response
from the server.
• The ClientRequest implements a Writable stream, so
it provides all the functionality of a Writable stream
object. For example, you can use the write() method
to write to it as well as pipe a Readable stream into it
• To implement a ClientRequest object, you use
a call to http.request() using the following
syntax: http.request(options, callback)
var http = require('http');
var options = {
hostname: 'www.myserver.com',
path: '/',
port: '8080',
method: 'POST' };
var req = http.request(options, function(response){
var str = ''
response.on('data', function (chunk)
{ str += chunk; });
response.on('end', function () {
console.log(str);
});
});
req.end();
Options that can be specified when creating
a ClientRequest
Events available on ClientRequest objects
Methods available on ClientRequest objects
The http.ServerResponse Object
• The ServerResponse object is created by the HTTP server
internally when a request event is received.
• It is passed to the request event handler as the second
argument. You use the ServerRequest object to formulate
and send a response to the client.
• The ServerResponse implements a Writable stream, so it
provides all the functionality of a Writable stream object.
• For example, you can use the write() method to write to
it as well as pipe a Readable stream into it to write data
back to the client.
Events available on ServerResponse objectsEvents available
on ServerResponse objects
Methods available on ServerResponse
objects
The http.IncomingMessage Object
• The IncomingMessage object is created either by the HTTP server or the HTTP
client.
• On the server side, the client request is represented by an IncomingMessage
object, and on the client side the server response is represented by an
IncomingMessage object.
• The IncomingMessage object can be used for both because the functionality is
basically the same.
• The IncomingMessage implements a Readable stream, allowing you to read the
client request or server response as a streaming source. This means that the
readable and data events can be listened to and used to read data from the
stream.
• The IncomingMessage implements a Readable stream, allowing you to read the
client request or server response as a streaming source. This means that the
readable and data events can be listened to and used to read data from the
stream.
Events, properties, and methods available on
IncomingMessage objects
The http.Server Object
• The Node.js HTTP Server object provides the fundamental
framework to implement HTTP servers.
• It provides an underlying socket that listens on a port and
handles receiving requests and then sends responses out to
client connections.
• While the server is listening, the Node.js application will not end.
The Server object implements EventEmitter and emits the events
listed in the previous chapter.
• As you implement an HTTP server, you need to handle at least
some or all of these events. For example, at a minimum you
need an event handler to handle the request event that is
triggered when a client request is received.
Events that can be triggered by Server
objects
• To start the HTTP server, you need to first create a
Server object using the createServer() method
shown below.
• This method returns the Server object.
• The optional requestListener parameter is a
callback that is executed when the request event is
triggered.
• The callback should accept two parameters. The
first is an IncomingMessage object representing
the client request, and the second is a
ServerResponse object you use to formulate and
send the response
• http.createServer([requestListener])
• Once you have created the Server object, you
can begin listening on it by calling the listen()
method on the Server object:
listen(port, [hostname], [backlog], [callback])
The first method listen(port, [hostname], [backlog],
[callback]) is the one that you will most likely use. The
following list describes each of the parameters:
• port: Specifies the port to listen on.
• hostname: Specifies when the hostname will accept
connections, and if omitted, the server will accept
connections directed to any IPv4 address (INADDR_ANY).
• backlog: Specifies the maximum number of pending
connections that are allowed to be queued. This defaults
to 511.
• callback: Specifies the callback handler to execute once
the server has begun listening on the specified port.
• The following code shows an example of
starting an HTTP server and listening on port
8080. Notice the request callback handler:
• var http = require('http');
http.createServer(function (req, res)
{ <> }).listen(8080);
• Two other methods can be used to listen for
connections through the file system. The first
accepts a path to a file to listen on, and the
second accepts an already open file descriptor
handle:
• listen(path, [callback])
• listen(handle, [callback])
• To stop the HTTP server from listening once it
has started, use the following close() method:
close([callback])
Implementing HTTP Clients and Servers in
Node.js
• Serving Static Files :
The most basic type of HTTP server is one that
serves static files. To serve static files from
Node.js, you need to first start the HTTP server
and listen on a port. Then in the request
handler, you open the file locally using the fs
module and write the file contents to
the response.
http_server_static.js: Implementing a basic static file Web Server
var fs = require('fs');
var http = require('http');
var url = require('url');
var ROOT_DIR = "html/";
http.createServer(function (req, res) {
var urlObj = url.parse(req.url, true, false);
fs.readFile(ROOT_DIR + urlObj.pathname, function (err,data) {
if (err) {
res.writeHead(404);
res.end(JSON.stringify(err));
return; }
res.writeHead(200);
res.end(data);
});
}).listen(8080);
http_client_static.js: Basic web client retrieving static files
var http = require('http');
var options = {
hostname: 'localhost',
port: '8080',
path: '/hello.html'
};
function handleResponse(response) {
var serverData = '';
response.on('data', function (chunk) {
serverData += chunk;
});
response.on('end', function () {
console.log(serverData);
});
}
http.request(options, function(response){
handleResponse(response);
}).end();
Hello.html
<html>
<head>
<title>Static Example</title>
</head>
<body>
<h1>Hello from a Static File</h1>
</body>
</html>
http_server_get.js: Implementing a basic
GET webserver
var http = require('http');
var messages = [ 'Hello World', 04 'From a basic Node.js server',
'Take Luck'];
http.createServer(function (req, res) {
res.setHeader("Content-Type", "text/html");
res.writeHead(200);
res.write('<html><head><title>Simple HTTP Server</title></head>');
res.write('<body>');
for (var idx in messages){
res.write('n<h1>' + messages[idx] + '</h1>');
}
res.end('n</body></html>');
}).listen(8080);
http_client_get.js: Basic web client that makes a GET request
var options = {
hostname: 'localhost',
port: '8080',
};
function handleResponse(response) {
var serverData = '';
response.on('data', function (chunk) {
serverData += chunk;
});
response.on('end', function() {
console.log("Response Status:", response.statusCode);
console.log("Response Headers:", response.headers);
console.log(serverData);
});
}
http.request(options, function(response){
handleResponse(response);
}).end
http_server_post.js: Implementing a basic HTTP server that
handles HTTP POST requests
var http = require('http');
var options = {
host: '127.0.0.1',
path: '/',
port: '8080',
method: 'POST‘ };
function readJSONResponse(response) {
var responseData = '';
response.on('data', function (chunk) {
responseData += chunk; });
response.on('end', function () {
var dataObj = JSON.parse(responseData);
console.log("Raw Response: " +responseData);
console.log("Message: " + dataObj.message);
console.log("Question: " + dataObj.question);
}); }
var req = http.request(options, readJSONResponse);
req.write('{"name":"Bilbo", "occupation":"Burgler"}');
req.end();
http_client_post.js: Basic HTTP client that sends JSON data
to the server using POST and handles the JSON response
var http = require('http');
02 var options = {
03 host: '127.0.0.1',
04 path: '/',
05 port: '8080',
06 method: 'POST'
07 };
08 function readJSONResponse (response) {
09 var responseData = '';
10 response.on('data', function (chunk) {
11 responseData += chunk;
12 });
13 response.on('end', function () {
14 var dataObj = JSON.parse(responseData);
15 console.log("Raw Response: " +responseData);
16 console.log("Message: " + dataObj.message);
17 console.log("Question: " + dataObj.question);
18 });
19 }
20 var req = http.request(options, readJSONResponse);
21 req.write('{"name":"Bilbo", "occupation":"Burgler"}');
22 req.end();

httpmodule in java script all methods.pptx

  • 1.
    http module • thehttp module is pretty low level • it is not difficult to implement a full webserver using just the http module. • It doesn’t provide calls to handle routing, cookies. • using the http module for is implementing backend web services for your applications to use.(That is where the http module becomes an invaluable tool in your arsenal.) • You can create basic HTTP servers that provide • an interface for communications behind your firewall and then basic HTTP clients that interact with those services. • Note:When you get to the Express, you will see the advantages it provides. caching, and so on
  • 5.
    • var url= require('url'); • var urlStr = 'http://user:pass@host.com:80/resource/path ?query=string#hash • var urlObj = url.parse(urlStr, true, false); • urlString = url.format(urlObj);
  • 9.
    Processing Query Stringsand Form Parameters • HTTP requests often include query strings in the URL or parameter data in the body for form submissions. • The query string can be obtained from the URL object defined in the previous section. The parameter data sent by a form request can be read out of the body of the client request.
  • 10.
    • The querystring and form parameters are just basic key-value pairs. • To actually consume these values in your Node.js webserver you need to convert the string into a JavaScript object using the parse() method from the querystring module: querystring.parse(str, [sep], [eq], [options])
  • 11.
    • The strparameter is the query or parameter string. • The sep parameter allows you to specify the separator character used. The default separator character is &. • The eq parameter allows you to specify the assignment character to use when parsing. • The default is =. The options parameter is an object with the property maxKeys that allows you to limit the number of keys the resulting object can contain. • The default is 1000. If you specify 0, there is no limit.
  • 12.
    • The followingshows an example of using parse() to parse a query string: • var qstring = require('querystring'); • var params = qstring.parse("name=Brad&color=red&color= blue"); • The params object created would be: {name: 'Brad', color: ['red', 'blue']}
  • 13.
    Understanding Request, Response,and Server Objects • To use the http module in Node.js applications, you first need to understand the request and response objects. • They provide the information and much of the functionality that comes into and out of the HTTP clients and servers. • Once you see the makeup of these objects— including properties, events, and methods they provide—it will be simple to implement your own HTTP servers and clients.
  • 14.
    • The followingsections cover the purpose and behavior of the ClientRequest, ServerResponse, IncomingMessage, and Server objects.
  • 15.
    The http.ClientRequest Object •The ClientRequest object is created internally when you call http.request() when building the HTTP client. • This object represents the request while it is in progress to the server. You use the ClientRequest object to initiate, monitor, and handle the response from the server. • The ClientRequest implements a Writable stream, so it provides all the functionality of a Writable stream object. For example, you can use the write() method to write to it as well as pipe a Readable stream into it
  • 16.
    • To implementa ClientRequest object, you use a call to http.request() using the following syntax: http.request(options, callback)
  • 17.
    var http =require('http'); var options = { hostname: 'www.myserver.com', path: '/', port: '8080', method: 'POST' }; var req = http.request(options, function(response){ var str = '' response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { console.log(str); }); }); req.end();
  • 18.
    Options that canbe specified when creating a ClientRequest
  • 19.
    Events available onClientRequest objects
  • 20.
    Methods available onClientRequest objects
  • 21.
    The http.ServerResponse Object •The ServerResponse object is created by the HTTP server internally when a request event is received. • It is passed to the request event handler as the second argument. You use the ServerRequest object to formulate and send a response to the client. • The ServerResponse implements a Writable stream, so it provides all the functionality of a Writable stream object. • For example, you can use the write() method to write to it as well as pipe a Readable stream into it to write data back to the client.
  • 22.
    Events available onServerResponse objectsEvents available on ServerResponse objects
  • 23.
    Methods available onServerResponse objects
  • 25.
    The http.IncomingMessage Object •The IncomingMessage object is created either by the HTTP server or the HTTP client. • On the server side, the client request is represented by an IncomingMessage object, and on the client side the server response is represented by an IncomingMessage object. • The IncomingMessage object can be used for both because the functionality is basically the same. • The IncomingMessage implements a Readable stream, allowing you to read the client request or server response as a streaming source. This means that the readable and data events can be listened to and used to read data from the stream. • The IncomingMessage implements a Readable stream, allowing you to read the client request or server response as a streaming source. This means that the readable and data events can be listened to and used to read data from the stream.
  • 26.
    Events, properties, andmethods available on IncomingMessage objects
  • 27.
    The http.Server Object •The Node.js HTTP Server object provides the fundamental framework to implement HTTP servers. • It provides an underlying socket that listens on a port and handles receiving requests and then sends responses out to client connections. • While the server is listening, the Node.js application will not end. The Server object implements EventEmitter and emits the events listed in the previous chapter. • As you implement an HTTP server, you need to handle at least some or all of these events. For example, at a minimum you need an event handler to handle the request event that is triggered when a client request is received.
  • 28.
    Events that canbe triggered by Server objects
  • 30.
    • To startthe HTTP server, you need to first create a Server object using the createServer() method shown below. • This method returns the Server object. • The optional requestListener parameter is a callback that is executed when the request event is triggered. • The callback should accept two parameters. The first is an IncomingMessage object representing the client request, and the second is a ServerResponse object you use to formulate and send the response
  • 31.
    • http.createServer([requestListener]) • Onceyou have created the Server object, you can begin listening on it by calling the listen() method on the Server object: listen(port, [hostname], [backlog], [callback])
  • 32.
    The first methodlisten(port, [hostname], [backlog], [callback]) is the one that you will most likely use. The following list describes each of the parameters: • port: Specifies the port to listen on. • hostname: Specifies when the hostname will accept connections, and if omitted, the server will accept connections directed to any IPv4 address (INADDR_ANY). • backlog: Specifies the maximum number of pending connections that are allowed to be queued. This defaults to 511. • callback: Specifies the callback handler to execute once the server has begun listening on the specified port.
  • 33.
    • The followingcode shows an example of starting an HTTP server and listening on port 8080. Notice the request callback handler: • var http = require('http'); http.createServer(function (req, res) { <> }).listen(8080);
  • 34.
    • Two othermethods can be used to listen for connections through the file system. The first accepts a path to a file to listen on, and the second accepts an already open file descriptor handle: • listen(path, [callback]) • listen(handle, [callback]) • To stop the HTTP server from listening once it has started, use the following close() method: close([callback])
  • 35.
    Implementing HTTP Clientsand Servers in Node.js • Serving Static Files : The most basic type of HTTP server is one that serves static files. To serve static files from Node.js, you need to first start the HTTP server and listen on a port. Then in the request handler, you open the file locally using the fs module and write the file contents to the response.
  • 36.
    http_server_static.js: Implementing abasic static file Web Server var fs = require('fs'); var http = require('http'); var url = require('url'); var ROOT_DIR = "html/"; http.createServer(function (req, res) { var urlObj = url.parse(req.url, true, false); fs.readFile(ROOT_DIR + urlObj.pathname, function (err,data) { if (err) { res.writeHead(404); res.end(JSON.stringify(err)); return; } res.writeHead(200); res.end(data); }); }).listen(8080);
  • 37.
    http_client_static.js: Basic webclient retrieving static files var http = require('http'); var options = { hostname: 'localhost', port: '8080', path: '/hello.html' }; function handleResponse(response) { var serverData = ''; response.on('data', function (chunk) { serverData += chunk; }); response.on('end', function () { console.log(serverData); }); } http.request(options, function(response){ handleResponse(response); }).end();
  • 38.
  • 39.
    http_server_get.js: Implementing abasic GET webserver var http = require('http'); var messages = [ 'Hello World', 04 'From a basic Node.js server', 'Take Luck']; http.createServer(function (req, res) { res.setHeader("Content-Type", "text/html"); res.writeHead(200); res.write('<html><head><title>Simple HTTP Server</title></head>'); res.write('<body>'); for (var idx in messages){ res.write('n<h1>' + messages[idx] + '</h1>'); } res.end('n</body></html>'); }).listen(8080);
  • 40.
    http_client_get.js: Basic webclient that makes a GET request var options = { hostname: 'localhost', port: '8080', }; function handleResponse(response) { var serverData = ''; response.on('data', function (chunk) { serverData += chunk; }); response.on('end', function() { console.log("Response Status:", response.statusCode); console.log("Response Headers:", response.headers); console.log(serverData); }); } http.request(options, function(response){ handleResponse(response); }).end
  • 41.
    http_server_post.js: Implementing abasic HTTP server that handles HTTP POST requests var http = require('http'); var options = { host: '127.0.0.1', path: '/', port: '8080', method: 'POST‘ }; function readJSONResponse(response) { var responseData = ''; response.on('data', function (chunk) { responseData += chunk; }); response.on('end', function () { var dataObj = JSON.parse(responseData); console.log("Raw Response: " +responseData); console.log("Message: " + dataObj.message); console.log("Question: " + dataObj.question); }); } var req = http.request(options, readJSONResponse); req.write('{"name":"Bilbo", "occupation":"Burgler"}'); req.end();
  • 42.
    http_client_post.js: Basic HTTPclient that sends JSON data to the server using POST and handles the JSON response var http = require('http'); 02 var options = { 03 host: '127.0.0.1', 04 path: '/', 05 port: '8080', 06 method: 'POST' 07 }; 08 function readJSONResponse (response) { 09 var responseData = ''; 10 response.on('data', function (chunk) { 11 responseData += chunk; 12 }); 13 response.on('end', function () { 14 var dataObj = JSON.parse(responseData); 15 console.log("Raw Response: " +responseData); 16 console.log("Message: " + dataObj.message); 17 console.log("Question: " + dataObj.question); 18 }); 19 } 20 var req = http.request(options, readJSONResponse); 21 req.write('{"name":"Bilbo", "occupation":"Burgler"}'); 22 req.end();