You are on page 1of 6

Express JS 16 April 2021

Express JS
 Node.js is an amazing tool for building networking services and
applications.
 Express is a Node.js Web Framework. ExpressJS is a web application
framework that provides you with a simple API to build websites, web
Express JS apps and back ends.
 It is flexible as there are numerous modules available on npm, which
Dr.V.Mareeswari can be directly plugged into Express.
Assistant Professsor(Sr)  Express was developed by TJ Holowaychuk and is maintained by
School of Information Technology and Engineering the Node.js foundation and numerous open source contributors.
VIT, Vellore
Cabin No:SJT 210-A30

2 Dr.Mareeswari V/ AP(Sr) / SITE / VIT

C:\Users\admin\marees_node_express1.js Explanation
 First, we import the express package to the express value.
const express = require('express')  We instantiate an application by calling its app() method. app.get(route, callback)
const app = express()  Once we have the application object, we tell it to listen for GET requests on the /path,
using the get() method.
app.get('/', (req, res) => res.send('Hello Mareeswari!'))  There is a method for every HTTP verb: get(), post(), put(), delete(), patch().
app.listen(3000, () => console.log(‘Your Express Server is ready'))  Those methods accept a callback function, which is called when a request is started, and we
need to handle it. An asynchronous function that is called when the server starts listening
for requests.
 Express sends us two objects in this callback, which we called req and res, that represent
the Request and the Response objects.
 Request is the HTTP request. It can give us all the info about that, including the request
parameters, the headers, the body of the request, and more. Response is the HTTP
response object that we’ll send to the client.
 What we do in this callback is to send the ‘Hello World!’ string to the client, using
the Response.send() method. This method sets that string as the body, and it closes the
connection.
Dr.Mareeswari V/ AP(Sr) / SITE / VIT
 The last line of the example actually starts the server, and tells it to listen on port 3000. We
Dr.Mareeswari V/ AP(Sr) / SITE / VIT
3 4
pass in a callback that is called when the server is ready to accept new requests.

Dr. Mareeswari V/ AP(Sr) / SITE / VIT 1


Express JS 16 April 2021

REQUEST PARAMETERS C:\Users\admin\marees_node_express_form.js


Property Description var http = require("http");
.app holds a reference to the Express app object
var express = require('express');
.baseUrl the base path on which the app responds
contains the data submitted in the request body (must be parsed and populated manually var app = express();
.body
before you can access it)
var bodyParser = require('body-parser');
.cookies contains the cookies sent by the request (needs the cookie-parser middleware)
.hostname the server hostname var urlencodedParser = bodyParser.urlencoded({ extended: true });
.ip the server IP // Running Server Details.
.method the HTTP method used
var server = app.listen(8080, function () {
.params the route named parameters
.path the URL path var host = server.address().address
.protocol the request protocol var port = server.address().port
.query an object containing all the query strings used in the request
.secure true if the request is secure (uses HTTPS)
console.log("Example app listening at %s:%s Port", host, port)});
.signedCookies contains the signed cookies sent by the request (needs the cookie-parser middleware)
5 Dr.Mareeswari V/ AP(Sr) / SITE / VIT 6 Dr.Mareeswari V/ AP(Sr) / SITE / VIT
.xhr true if the request is an XMLHttpRequest

app.get('/form', function (req, res) { app.post('/thank', urlencodedParser, function (req, res){


var html=''; var reply='';
html +="<body>";
reply += "Your name is" + req.body.name;
html += "<form action='/thank' method='post' name='form1'>";
html += "Name:</p><input type= 'text' name='name'>";
reply += "Your E-mail id is" + req.body.email;
html += "Email:</p><input type='text' name='email'>"; reply += "Your address is" + req.body.address;
html += "address:</p><input type='text' name='address'>"; reply += "Your mobile number is" + req.body.mobilno;
html += "Mobile number:</p><input type='text' res.send(reply); }); // response to the client browser window
name='mobilno'>";
html += "<input type='submit' value='submit'>";
html += "<INPUT type='reset' value='reset'>";
html += "</form>";
html += "</body>";
res.send(html);});
7 Dr.Mareeswari V/ AP(Sr) / SITE / VIT 8 Dr.Mareeswari V/ AP(Sr) / SITE / VIT

Dr. Mareeswari V/ AP(Sr) / SITE / VIT 2


Express JS 16 April 2021

In Visual Code
F:\Academic\Web Technologies\ITE1002\Programs\Node JS\index.js
let express = require('express')
let app = express()
app.get('/add', (req, res) =>
{
Run node index.js in
let n1=parseInt(req.query.num1);
Terminal
let n2=parseInt(req.query.num2); http://localhost:3000
let result=n1+n2; /add?num1=100&nu
res.send('Addition:'+result); m2=20 in chrome
});
app.listen(3000);

9 Dr.Mareeswari V/ AP(Sr) / SITE / VIT 10 Dr.Mareeswari V/ AP(Sr) / SITE / VIT

F:\Academic\Web Technologies\ITE1002\Programs\Node
JS\home.html
<html> <body> <h1>Hello</h1>
<form action="/name" method="GET">
<input type="text" name="t1">
<button>SEND</button> </form>

<form action="/add" method="GET">


<input type="text" name="num1">
<input type="text" name="num2">
<button>ADD</button>
</form> </body> </html>

11 Dr.Mareeswari V/ AP(Sr) / SITE / VIT 12 Dr.Mareeswari V/ AP(Sr) / SITE / VIT

Dr. Mareeswari V/ AP(Sr) / SITE / VIT 3


Express JS 16 April 2021

F:\Academic\Web Technologies\ITE1002\Programs\Node
JS\index.js
let express = require('express')
let server = express()
let path=require('path')
server.get('/home',(req,res)=>{
res.sendFile(path.join(__dirname,'home.html'))})
server.get('/name',(req,res)=>{
res.send('Hello '+req.query.t1)})
server.get('/add', (req, res) => {
let n1=parseInt(req.query.num1);
let n2=parseInt(req.query.num2);
let result=n1+n2;
res.send('Addition: '+result);});
server.listen(3000);
console.log("Server is ready"); Dr.Mareeswari V/ AP(Sr) / SITE / VIT 14 Dr.Mareeswari V/ AP(Sr) / SITE / VIT
13

15 Dr.Mareeswari V/ AP(Sr) / SITE / VIT 16 Dr.Mareeswari V/ AP(Sr) / SITE / VIT

Dr. Mareeswari V/ AP(Sr) / SITE / VIT 4


Express JS 16 April 2021

 Now to use cookies with Express, we will require the cookie-parser.


Handling Cookie cookie-parser is a middleware which parses cookies attached to the client
 Cookies are simple, small files/data that are sent to client with a request object. To use it, we will require it in our index.js file; this can
server request and stored on the client side. Every time the user be used the same way as we use other middleware. Here, we will use
loads the website back, this cookie is sent with the request. This the following code.
helps us keep track of the user’s actions. var cookieParser = require('cookie-parser');
app.use(cookieParser());
 The following are the numerous uses of the HTTP Cookies −
 cookie-parser parses Cookie header and populates req.cookies with
 Session management an object keyed by the cookie names. To set a new cookie, let us define
 Personalization(Recommendation systems) a new route in your Express app like −
 User tracking var express = require('express');
 To use cookies with Express, we need the cookie-parser middleware. var app = express();
To install it, use the following code − app.get('/', function(req, res){
 npm install --save cookie-parser
res.cookie('name', 'marees').send('cookie set'); //Sets name =marees
}); app.listen(3000);
17 Dr.Mareeswari V/ AP(Sr) / SITE / VIT 18 Dr.Mareeswari V/ AP(Sr) / SITE / VIT

 To check if your cookie is set or not, just go to your browser, fire up C:\Users\admin\marees_node_cookie_expre
the console, and enter − ss.js
console.log(document.cookie);
var express = require('express')
 You will get the output like (you may have more cookies set maybe
// npm install cookie-parser
due to extensions in your browser) −
var cookieParser = require('cookie-parser')
"name = marees"
var app = express();
 The browser also sends back cookies every time it queries the server.
To view cookies from your server, on the server console in a route, // need cookieParser middleware before we can do anything with
add the following code to that route. cookies
console.log('Cookies:',req.cookies); app.use(cookieParser());
 Next time you send a request to this route, you will receive the // set a cookie
following output. app.use(function (req, res, next) {
Cookies:{ name:'marees' } // check if client sent cookie
var cookie = req.cookies.cookieName; // RETRIEVE THE COOKIES
19 Dr.Mareeswari V/ AP(Sr) / SITE / VIT 20 Dr.Mareeswari V/ AP(Sr) / SITE / VIT

Dr. Mareeswari V/ AP(Sr) / SITE / VIT 5


Express JS 16 April 2021

if (cookie === undefined) {// no: set a new cookie Install cookie-parser, running server and
var randomNumber=Math.random().toString(); running client
randomNumber=randomNumber.substring(2,randomNumber.length);
res.cookie('cookieName',randomNumber, { maxAge: 900000, httpOnly:
true });
console.log('cookie created successfully');
} else
{ // yes, cookie was already present
console.log('cookie exists', cookie);
}next(); }); // <-- important!
app.get('/', function(req, res) {
res.send(JSON.stringify(req.cookies));
}) app.listen(8081)
21 Dr.Mareeswari V/ AP(Sr) / SITE / VIT 22 Dr.Mareeswari V/ AP(Sr) / SITE / VIT

Adding Cookies with Expiration Time Deleting Existing Cookies


 You can add cookies that expire. To add a cookie that expires, just pass
 To delete a cookie, use the clearCookie function. For example, if you
an object with property 'expire' set to the time when you want it to
need to clear a cookie named foo, use the following code.
expire. For example,
var express = require('express');
 //Expires after 360000 ms from the time it is set.
var app = express();
res.cookie(name, 'value', {expire: 360000 + Date.now()});
app.get('/clear_cookie_foo',function(req, res){
 Another way to set expiration time is using 'maxAge' property.
Using this property, we can provide relative time instead of absolute res.clearCookie('foo');
time. Following is an example of this method. res.send('cookie foo cleared'); });
 //This cookie also expires after 360000 ms from the time it is set. app.listen(3000);
res.cookie(name, 'value', {maxAge: 360000});

23 Dr.Mareeswari V/ AP(Sr) / SITE / VIT 24 Dr.Mareeswari V/ AP(Sr) / SITE / VIT

Dr. Mareeswari V/ AP(Sr) / SITE / VIT 6

You might also like