Event Handling- GET & POST
implementation
What is Node.js?
• Node.js is an open source server environment
• Node.js is free
• Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.)
• Node.js uses JavaScript on the server
What Can Node.js Do?
• Node.js can generate dynamic page content
• Node.js can create, open, read, write, delete, and close files on the server
• Node.js can collect form data
• Node.js can add, delete, modify data in your database
What is a Node.js File?
• Node.js files contain tasks that will be executed on certain events
• A typical event is used to access a port on the server
• Node.js files must be initiated on the server before having any effect
• Node.js files have extension ".js"
Why Node.js?
how PHP or ASP handles a file request:
• Sends the task to the computer's file system.
• Waits while the file system opens and reads the file.
• Returns the content to the client.
• Ready to handle the next request.
how Node.js handles a file request:
• Sends the task to the computer's file system.
• Ready to handle the next request.
• When the file system has opened and read the file, the server returns the
content to the client.
• Node.js eliminates the waiting, and simply continues with the next request.
A common task for a web
server can be to open a file
on the server and return the
content to the client.
•Node.js runs single-threaded, non-blocking,
asynchronous programming, which is very memory
efficient.
Example : Web Servers
• https://www.linode.com/docs/guides/web-servers-list/#the-web-
servers-list
Getting Started
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.end('Hello World!');
}).listen(8080);
file named "myfirst.js
Initiate the Node.js File
Initiate "myfirst.js":
C:UsersYour Name>node myfirst.js
Now, your computer works as a server!
If anyone tries to access your computer on port 8080, they will get a
"Hello World!" message in return!
Start your internet browser, and type in the address:
http://localhost:8080
What is a Module in Node.js?
• Consider modules to be the same as JavaScript libraries.
• A set of functions you want to include in your application.
Built-in Modules
• Node.js has a set of built-in modules which you can use without any
further installation.
• Look at our Built-in Modules Reference for a complete list of modules.
Include Modules
• To include a module, use the require() function with the name of the
module:
var http = require('http');
Create Your Own Modules
• The following example creates a module that returns a date and time
object:
Example
• Get your own Node.js Server
• Create a module that returns the current date and time:
exports.myDateTime = function () {
return Date();
};
exports keyword to make properties and methods available
outside the module file.
Save the code above in a file called "myfirstmodule.js"
Include Your Own Module
var http = require('http');
var dt = require('./myfirstmodule');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
res.write("The date and time are currently: " + dt.myDateTime());
res.end();
}).listen(8080);
Notice that we use ./ to locate the module, that means that the
module is located in the same folder as the Node.js file.
Save the code above in a file called "demo_module.js", and initiate the
file:
Node.js as a Web Server
• The HTTP module can create an HTTP server that listens to server ports
and gives a response back to the client.
1. Use the createServer() method to create an HTTP server
2. res.writeHead() method is the status code, 200 means that all is OK,
the second argument is an object containing the response headers.
3. http.createServer() has a req argument that represents the request
from the client, as an object (http.IncomingMessage object).
4. This object has a property called "url" which holds the part of the url
that comes after the domain name
What is Query String
• A query string is a part of the uniform resource locator (URL), that
assigns values to specified parameters.
https://example.com/over/there?name=ferret
https://example.com/path/to/page?name=ferret&color=purple
• Copy Code
• The query string in first case is name=ferret and in second case is
name=ferret&color=purple
Node.js Events
• In Node.js applications, Events and Callbacks concepts are used to
provide concurrency.
• As Node.js applications are single threaded and every API of Node js
are asynchronous.
• So it uses async function to maintain the concurrency. Node uses
observer pattern.
• Node thread keeps an event loop and after the completion of any
task, it fires the corresponding event which signals the event
listener function to get executed
Event Driven Programming
• It means as soon as Node starts its server, it simply initiates its
variables, declares functions and then simply waits for event to occur.
• It is the one of the reason why Node.js is pretty fast compared to other
similar technologies.
• There is a main loop in the event driven application that listens for
events, and then triggers a callback function when one of those events
is detected.
Events and Callbacks
• callback functions are called when an asynchronous function
returns its result
• where as event handling works on the observer pattern.
Whenever an event gets fired, its listener function starts
executing.
• Node.js has multiple in-built events available through events
module and EventEmitter class which is used to bind events
and event listeners.
• In node.js an event can be described simply as a string with a
corresponding callback.
• An event can be "emitted" (or in other words, the corresponding
callback be called) multiple times or you can choose to only listen for
the first time it is emitted.
• The on or addListener method (basically the subscription method)
allows you to choose the event to watch for and the callback to be
called.
• The emit method (the publish method), on the other hand, allows
you to "emit" an event, which causes all callbacks registered to the
event to 'fire', (get called).
• When the EventEmitter object emits an event, all of the functions
attached to that specific event are called synchronously. Any values
returned by the called listeners are ignored and will be discarded.
•Node.js uses events module to create and handle
custom events.
•The EventEmitter class can be used to create and
handle custom events module.
What is GET?
• GET method is used to appends form data to the URL in
name or value pair.
• If you use GET, the length of URL will remain limited.
• It helps users to submit the bookmark the result.
• GET is better for the data which does not require any security
or having images or word documents.
Features of GET
• It is very easy to bookmark data using GET method.
• The length restriction of GET method is limited.
• You can use this method only to retrieve data from the
address bar in the browser.
• This method enables you to easily store the data.
GET Method Example
GET/RegisterStudent.asp?user=value1&pass=value2
Advantages of GET
• The GET method can retrieve information identified by the
request-URl (Uniform Resource Identifier).
• GET requests can be viewed in the browser history.
• It enables you to save the results of a HTML form.
• You can easily use GET method to request required data.
What is POST?
• POST is a method that is supported by HTTP and depicts that
a web server accepts the data included in the body of the
message.
• POST is often used by World Wide Web to send user
generated data to the web server or when you upload file.
Features of POST
• POST method request gets input from the request body and query
string.
• Data passed using the POST method will not visible in query
parameters in browser URL.
• parameters of POST methods are not saved in browser history.
• There is no restriction in sending the length of data.
• It helps you to securely pass sensitive and confidential information
like login details to server.
POST Method Example
POST/RegisterStudent.asp HTTP/1.1
Host: www.guru99.com
user=value1&pass=value2
Advantages of POST
• This method helps you to determine resource URI.
• Specifying a new resource location header is very easy using location header.
• You can send a request to accept the entity as a new resource, which is identified by
the URI.
• You can send user-generated data to the web server.
• It is very useful when you do not have any idea about the resource you have to keep in
the URL.
• Use POST when you need the server, which controls URL generation of your resources.
• POST is a secure method as its requests do not remain in browser history.
• You can effortlessly transmit a large amount of data using post.
• You can keep the data private.
• This method can be used to send binary as well as ASCII data.
Disadvantages of GET
• GET can’t be used to send word documents or images.
• GET requests can be used only to retrieve data
• The GET method cannot be used for passing sensitive information like
usernames and passwords.
• The length of the URL is limited.
• If you use GET method, the browser appends the data to the URL.
• You can easily bookmark Query string value in GET
Disadvantages of POST
• It is not possible to save data as the data sent by the POST method is
not visible in the URL.
• You cannot see POST requests in browser history.
• This method is not compatible with many firewall setups.
• You cannot use spaces, tabs, carnage returns, etc.
• This method is not compatible with some firewall setups.
• POST method takes lots of time when uploading the large binary file.
two different types of HTTP request methods
HTTP GET HTTP POST
In GET method we can not send large amount of data
rather limited data is sent because the request
parameter is appended into the URL.
In POST method large amount of data can be sent
because the request parameter is appended into the
body.
GET request is comparatively less secure because the
data is exposed in the URL bar.
POST request is comparatively more secure because the
data is not exposed in the URL bar.
Request made through GET method are stored in
Browser history.
Request made through POST method is not stored in
Browser history.
GET method request can be saved as bookmark in
browser.
POST method request can not be saved as bookmark in
browser.
Request made through GET method are stored in cache
memory of Browser.
Request made through POST method are not stored in
cache memory of Browser.
Data passed through GET method can be easily stolen by
attackers.
Data passed through POST method can not be easily
stolen by attackers.
In GET method only ASCII characters are allowed. In POST method all types of data is allowed.
Node.js URL.pathname API
• url module is used to get and set the pathname portion of
the URL.
Syntax:
const url.pathname
Node.js querystring.parse() Method
•It is used to parse a URL query string into an object
that contains the key and pair values of the query
URL.
•To decode alternative character encoding, the
decodeURIComponent option has to be specified.
Syntax:
querystring.parse( str[, sep[, eq[, options]]]) )
• str: It is a String that specifies the URL query that has to be parsed.
• sep: It is a String that specifies the substring used to delimit the key and value pairs in the
specified query string. The default value is “&”.
• eq: It is a String that specifies the substring used to delimit keys and values in the specified
query string. The default value is “=”.
• options: It is an object which can be used to modify the behavior of the method. It has the
following parameters:
• decodeURIComponent: It is a function that would be used to decode percent-encoded
characters in the query string. The default value is querystring.unescape().
• maxKeys: It is a number which specifies the maximum number of keys that should be parsed
from the query string. A value of “0” would remove all the counting limits. The default value is
“1000”.
Client side : HTML , CSS
<html>
<body>
<form action="http://127.0.0.1:3333/Login" method="GET">
Enter your user Name: <input type="text" name="username" value=""/> <br/>
Enter your email: <input type="text" name="email" value=""/>
<input type="submit" name=login value="Login">
</form>
</body>
</html>
Server Side
http=require("http")
url=require("url")
qs=require("querystring")
function onRequest(request,response)
{ var path=url.parse(request.url).pathname;
console.log("Request for " + path + "received");
var query = url.parse(request.url).query;
var name=qs.parse(query)["username"];
var email=qs.parse(query)["email"];
response.write("Hello" + name +" your email id " + email+"success");
response.end();
} http.createServer(onRequest).listen(3333);
console.log("server has started");
Running in the Command Line Interface
console.log('This example is different!');
console.log('The result is displayed in the Command Line Interface');
<html>
<head>
<title></title>
</head>
<body>
<form action="http://localhost:4001">
Enter n1:<input type="text" name="n1" value=""/><br>
Enter n2:<input type="text" name="n2" value=""/><br>
<input type="submit" value="Login"/>
</form>
</body>
</html>
http=require('http');
url=require('url');
querystring = require('querystring');
function onRequest(req,res){
var path = url.parse(req.url).pathname;
var query =url.parse(req.url).query;
var no1 =querystring.parse(query)["n1"];
var no2=querystring.parse(query)["n2"];
var sum=parseInt(no1)+parseInt(no2);
console.log(sum);
res.write("The result is "+" " + sum);
res.end();
}
http.createServer(onRequest).listen(4001);
console.log('Server has Started.......');
<html>
<head>
<title></title>
</head>
<body>
<form action=http://localhost:4001 method=“POST”>
Enter n1:<input type="text" name="n1" value=""/><br>
Enter n2:<input type="text" name="n2" value=""/><br>
<input type="submit" value="Login"/>
</form>
</body>
</html>
http=require('http');
querystring = require('querystring');
var qs,no1,no2;
http.createServer(function(req,res){
var data1='';
req.on('data',function(chunk){
console.log(chunk);
data1+=chunk;
});
req.on('end',function(){qs=querystring.parse(data1);
console.log(qs);
no1=qs['n1']
no2=qs['n2']
var sum=parseInt(no1)+parseInt(no2);
res.write("The result" + sum);
res.end();
});
}).listen(3000); console.log('Server has Started.......');
post() will process the request parameters
using on() method of EventEmitter class and
build-in events like ‘data’ and ‘end’.
‘data’ event is used to read the
request parameters
• ‘end’ event is invoked once
‘data’ event is completed to
process the data retrieved using
‘data’ event

Event Handling -_GET _ POSTimplementation.pptx

  • 1.
    Event Handling- GET& POST implementation
  • 2.
    What is Node.js? •Node.js is an open source server environment • Node.js is free • Node.js runs on various platforms (Windows, Linux, Unix, Mac OS X, etc.) • Node.js uses JavaScript on the server
  • 3.
    What Can Node.jsDo? • Node.js can generate dynamic page content • Node.js can create, open, read, write, delete, and close files on the server • Node.js can collect form data • Node.js can add, delete, modify data in your database
  • 4.
    What is aNode.js File? • Node.js files contain tasks that will be executed on certain events • A typical event is used to access a port on the server • Node.js files must be initiated on the server before having any effect • Node.js files have extension ".js"
  • 5.
    Why Node.js? how PHPor ASP handles a file request: • Sends the task to the computer's file system. • Waits while the file system opens and reads the file. • Returns the content to the client. • Ready to handle the next request. how Node.js handles a file request: • Sends the task to the computer's file system. • Ready to handle the next request. • When the file system has opened and read the file, the server returns the content to the client. • Node.js eliminates the waiting, and simply continues with the next request. A common task for a web server can be to open a file on the server and return the content to the client.
  • 6.
    •Node.js runs single-threaded,non-blocking, asynchronous programming, which is very memory efficient.
  • 7.
    Example : WebServers • https://www.linode.com/docs/guides/web-servers-list/#the-web- servers-list
  • 8.
    Getting Started var http= require('http'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.end('Hello World!'); }).listen(8080); file named "myfirst.js
  • 9.
    Initiate the Node.jsFile Initiate "myfirst.js": C:UsersYour Name>node myfirst.js Now, your computer works as a server! If anyone tries to access your computer on port 8080, they will get a "Hello World!" message in return! Start your internet browser, and type in the address: http://localhost:8080
  • 10.
    What is aModule in Node.js? • Consider modules to be the same as JavaScript libraries. • A set of functions you want to include in your application.
  • 11.
    Built-in Modules • Node.jshas a set of built-in modules which you can use without any further installation. • Look at our Built-in Modules Reference for a complete list of modules. Include Modules • To include a module, use the require() function with the name of the module: var http = require('http');
  • 12.
    Create Your OwnModules • The following example creates a module that returns a date and time object: Example • Get your own Node.js Server • Create a module that returns the current date and time: exports.myDateTime = function () { return Date(); }; exports keyword to make properties and methods available outside the module file. Save the code above in a file called "myfirstmodule.js"
  • 13.
    Include Your OwnModule var http = require('http'); var dt = require('./myfirstmodule'); http.createServer(function (req, res) { res.writeHead(200, {'Content-Type': 'text/html'}); res.write("The date and time are currently: " + dt.myDateTime()); res.end(); }).listen(8080); Notice that we use ./ to locate the module, that means that the module is located in the same folder as the Node.js file. Save the code above in a file called "demo_module.js", and initiate the file:
  • 14.
    Node.js as aWeb Server • The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client. 1. Use the createServer() method to create an HTTP server 2. res.writeHead() method is the status code, 200 means that all is OK, the second argument is an object containing the response headers. 3. http.createServer() has a req argument that represents the request from the client, as an object (http.IncomingMessage object). 4. This object has a property called "url" which holds the part of the url that comes after the domain name
  • 15.
    What is QueryString • A query string is a part of the uniform resource locator (URL), that assigns values to specified parameters. https://example.com/over/there?name=ferret https://example.com/path/to/page?name=ferret&color=purple • Copy Code • The query string in first case is name=ferret and in second case is name=ferret&color=purple
  • 16.
    Node.js Events • InNode.js applications, Events and Callbacks concepts are used to provide concurrency. • As Node.js applications are single threaded and every API of Node js are asynchronous. • So it uses async function to maintain the concurrency. Node uses observer pattern. • Node thread keeps an event loop and after the completion of any task, it fires the corresponding event which signals the event listener function to get executed
  • 17.
    Event Driven Programming •It means as soon as Node starts its server, it simply initiates its variables, declares functions and then simply waits for event to occur. • It is the one of the reason why Node.js is pretty fast compared to other similar technologies. • There is a main loop in the event driven application that listens for events, and then triggers a callback function when one of those events is detected.
  • 18.
    Events and Callbacks •callback functions are called when an asynchronous function returns its result • where as event handling works on the observer pattern. Whenever an event gets fired, its listener function starts executing. • Node.js has multiple in-built events available through events module and EventEmitter class which is used to bind events and event listeners.
  • 19.
    • In node.jsan event can be described simply as a string with a corresponding callback. • An event can be "emitted" (or in other words, the corresponding callback be called) multiple times or you can choose to only listen for the first time it is emitted. • The on or addListener method (basically the subscription method) allows you to choose the event to watch for and the callback to be called. • The emit method (the publish method), on the other hand, allows you to "emit" an event, which causes all callbacks registered to the event to 'fire', (get called). • When the EventEmitter object emits an event, all of the functions attached to that specific event are called synchronously. Any values returned by the called listeners are ignored and will be discarded.
  • 20.
    •Node.js uses eventsmodule to create and handle custom events. •The EventEmitter class can be used to create and handle custom events module.
  • 22.
    What is GET? •GET method is used to appends form data to the URL in name or value pair. • If you use GET, the length of URL will remain limited. • It helps users to submit the bookmark the result. • GET is better for the data which does not require any security or having images or word documents.
  • 23.
    Features of GET •It is very easy to bookmark data using GET method. • The length restriction of GET method is limited. • You can use this method only to retrieve data from the address bar in the browser. • This method enables you to easily store the data.
  • 24.
  • 25.
    Advantages of GET •The GET method can retrieve information identified by the request-URl (Uniform Resource Identifier). • GET requests can be viewed in the browser history. • It enables you to save the results of a HTML form. • You can easily use GET method to request required data.
  • 26.
    What is POST? •POST is a method that is supported by HTTP and depicts that a web server accepts the data included in the body of the message. • POST is often used by World Wide Web to send user generated data to the web server or when you upload file.
  • 27.
    Features of POST •POST method request gets input from the request body and query string. • Data passed using the POST method will not visible in query parameters in browser URL. • parameters of POST methods are not saved in browser history. • There is no restriction in sending the length of data. • It helps you to securely pass sensitive and confidential information like login details to server.
  • 28.
    POST Method Example POST/RegisterStudent.aspHTTP/1.1 Host: www.guru99.com user=value1&pass=value2
  • 29.
    Advantages of POST •This method helps you to determine resource URI. • Specifying a new resource location header is very easy using location header. • You can send a request to accept the entity as a new resource, which is identified by the URI. • You can send user-generated data to the web server. • It is very useful when you do not have any idea about the resource you have to keep in the URL. • Use POST when you need the server, which controls URL generation of your resources. • POST is a secure method as its requests do not remain in browser history. • You can effortlessly transmit a large amount of data using post. • You can keep the data private. • This method can be used to send binary as well as ASCII data.
  • 30.
    Disadvantages of GET •GET can’t be used to send word documents or images. • GET requests can be used only to retrieve data • The GET method cannot be used for passing sensitive information like usernames and passwords. • The length of the URL is limited. • If you use GET method, the browser appends the data to the URL. • You can easily bookmark Query string value in GET
  • 31.
    Disadvantages of POST •It is not possible to save data as the data sent by the POST method is not visible in the URL. • You cannot see POST requests in browser history. • This method is not compatible with many firewall setups. • You cannot use spaces, tabs, carnage returns, etc. • This method is not compatible with some firewall setups. • POST method takes lots of time when uploading the large binary file.
  • 32.
    two different typesof HTTP request methods HTTP GET HTTP POST In GET method we can not send large amount of data rather limited data is sent because the request parameter is appended into the URL. In POST method large amount of data can be sent because the request parameter is appended into the body. GET request is comparatively less secure because the data is exposed in the URL bar. POST request is comparatively more secure because the data is not exposed in the URL bar. Request made through GET method are stored in Browser history. Request made through POST method is not stored in Browser history. GET method request can be saved as bookmark in browser. POST method request can not be saved as bookmark in browser. Request made through GET method are stored in cache memory of Browser. Request made through POST method are not stored in cache memory of Browser. Data passed through GET method can be easily stolen by attackers. Data passed through POST method can not be easily stolen by attackers. In GET method only ASCII characters are allowed. In POST method all types of data is allowed.
  • 33.
    Node.js URL.pathname API •url module is used to get and set the pathname portion of the URL. Syntax: const url.pathname
  • 34.
    Node.js querystring.parse() Method •Itis used to parse a URL query string into an object that contains the key and pair values of the query URL. •To decode alternative character encoding, the decodeURIComponent option has to be specified.
  • 35.
    Syntax: querystring.parse( str[, sep[,eq[, options]]]) ) • str: It is a String that specifies the URL query that has to be parsed. • sep: It is a String that specifies the substring used to delimit the key and value pairs in the specified query string. The default value is “&”. • eq: It is a String that specifies the substring used to delimit keys and values in the specified query string. The default value is “=”. • options: It is an object which can be used to modify the behavior of the method. It has the following parameters: • decodeURIComponent: It is a function that would be used to decode percent-encoded characters in the query string. The default value is querystring.unescape(). • maxKeys: It is a number which specifies the maximum number of keys that should be parsed from the query string. A value of “0” would remove all the counting limits. The default value is “1000”.
  • 36.
    Client side :HTML , CSS <html> <body> <form action="http://127.0.0.1:3333/Login" method="GET"> Enter your user Name: <input type="text" name="username" value=""/> <br/> Enter your email: <input type="text" name="email" value=""/> <input type="submit" name=login value="Login"> </form> </body> </html>
  • 37.
    Server Side http=require("http") url=require("url") qs=require("querystring") function onRequest(request,response) {var path=url.parse(request.url).pathname; console.log("Request for " + path + "received"); var query = url.parse(request.url).query; var name=qs.parse(query)["username"]; var email=qs.parse(query)["email"]; response.write("Hello" + name +" your email id " + email+"success"); response.end(); } http.createServer(onRequest).listen(3333); console.log("server has started");
  • 38.
    Running in theCommand Line Interface console.log('This example is different!'); console.log('The result is displayed in the Command Line Interface');
  • 39.
    <html> <head> <title></title> </head> <body> <form action="http://localhost:4001"> Enter n1:<inputtype="text" name="n1" value=""/><br> Enter n2:<input type="text" name="n2" value=""/><br> <input type="submit" value="Login"/> </form> </body> </html>
  • 40.
    http=require('http'); url=require('url'); querystring = require('querystring'); functiononRequest(req,res){ var path = url.parse(req.url).pathname; var query =url.parse(req.url).query; var no1 =querystring.parse(query)["n1"]; var no2=querystring.parse(query)["n2"]; var sum=parseInt(no1)+parseInt(no2); console.log(sum); res.write("The result is "+" " + sum); res.end(); } http.createServer(onRequest).listen(4001); console.log('Server has Started.......');
  • 41.
    <html> <head> <title></title> </head> <body> <form action=http://localhost:4001 method=“POST”> Entern1:<input type="text" name="n1" value=""/><br> Enter n2:<input type="text" name="n2" value=""/><br> <input type="submit" value="Login"/> </form> </body> </html>
  • 42.
    http=require('http'); querystring = require('querystring'); varqs,no1,no2; http.createServer(function(req,res){ var data1=''; req.on('data',function(chunk){ console.log(chunk); data1+=chunk; }); req.on('end',function(){qs=querystring.parse(data1); console.log(qs); no1=qs['n1'] no2=qs['n2'] var sum=parseInt(no1)+parseInt(no2); res.write("The result" + sum); res.end(); }); }).listen(3000); console.log('Server has Started.......'); post() will process the request parameters using on() method of EventEmitter class and build-in events like ‘data’ and ‘end’. ‘data’ event is used to read the request parameters • ‘end’ event is invoked once ‘data’ event is completed to process the data retrieved using ‘data’ event