0% found this document useful (0 votes)
255 views

Unit-4 Express Js

Uploaded by

TrendVidz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
255 views

Unit-4 Express Js

Uploaded by

TrendVidz
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Unit-4 Express.

js

Express.js is a web framework for Node.js. It is a fast, robust and asynchronous in nature.

What is Express.js
• Express is a fast, assertive, essential and moderate web framework of Node.js.
• Assume express as a layer built on the top of the Node.js that helps manage a server and
routes
• It provides a robust set of features to develop web and mobile applications.

Features of Express
o It can be used to design single-page, multi-page and hybrid web applications.
o It allows to setup middleware to respond to HTTP Requests.
o It defines a routing table which is used to perform different actions based on HTTP
method and URL.
o It allows to dynamically render HTML Pages based on passing arguments to
templates.

Why use Express


o Ultra fast I/O
o Asynchronous and single threaded
o MVC like structure
o Robust API makes routing easy

ExpressJS - Environment
Assuming that you have installed node.js on your system, the following steps
should be followed to install express on your Windows:
STEP-1: Creating a directory for our project and make that our working directory.
$ mkdir express_practice
$ cd express_practice

STEP-2: Using npm init command to create a package.json file for our project.
$ npm init

STEP-3: Installing Express


Now in your express_practice(name of your folder) folder type the following
command line:
$ npm install express
Create a new file called index.js and type the following in it.
Index.js
var express = require('express');
var app = express();

app.get('/', function(req, res){


res.send("Hello world!");
});

app.listen(6000);

Save the file, go to your terminal and type the following.


Node index.js
This will start the server. To test this app, open your browser and go to http://localhost:3000 and a
message will be displayed as in the following screenshot.

Request & Response


Express application uses a callback function whose parameters are request and response objects.

app.get('/', function (req, res) {


// --
})
Request Object − The request object represents the HTTP request and has properties for the request query
string, parameters, body, HTTP headers, and so on.
Response Object − The response object represents the HTTP response that an Express app sends when it
gets an HTTP request.

Response methods
The methods on the response object (res) in the following table can send a response to the client.
Method Description

res.end() End the response process.

res.json() Send a JSON response.

res.redirect() Redirect a request.

res.render() Render a view template.

res.send() Send a response of various types.

res.sendFile() Send a file as an octet stream.

Example
index.js
const expr = require("express");

const app = expr();

app.get ("/", (req,res)=>

{ res.set ("content-type","text/plain");

res.send ("<h1>Hello</h1>");

});

app.get ("/about", (req,res)=>

{ res.set ("content-type","text/html");

res.write ("Hello");

res.send ("<h1> Hello from home</h1>");

});

app.listen (5000,()=>

{ console.log ("server started");


})

Example: if you want to display page not found error .

const expr=require("express");
const app=expr();
app.get("/",(req,res)=>
{
res.write("hello");
res.send();
})
app.get("/about",(req,res)=>
{
res.write("world");
res.send();
})
app.get("*",(req,res)=>
{
res.status(404).send("page not found");
})
app.listen(5001,()=>
{
console.log("server started");
});

Routing
Routing refers to determining how an application responds to a client request to a particular endpoint,
which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).

Each route can have one or more handler functions, which are executed when the route is matched.

Route definition takes the following structure:


app.METHOD(PATH, HANDLER)

Where:

• app is an instance of express.


• METHOD is an HTTP request method, in lowercase.
• PATH is a path on the server.
• HANDLER is the function executed when the route is matched.

Respond with Hello World! on the homepage:


app.get('/', (req, res) => {
res.send('Hello World!')
})
Respond to POST request on the root route (/), the application’s home page:
app.post('/', (req, res) => {
res.send('Got a POST request')
})

The app.all() function is used to route all types of HTTP requests. Like if we have POST, GET, PUT, DELETE,
etc, requests made to any specific route, let’s say /user, so instead of defining different APIs like
app.post(‘/user’), app.get(‘/user’), etc, we can define single API app.all(‘/user’) which will accept all type
of HTTP request.
app.all('/', function(req, res){
res.send("HTTP method doesn't have any effect on this route!");
});

Route parameters
Route parameters are named URL segments that are used to capture the values specified at their position
in the URL. The captured values are populated in the req.params object, with the name of the route
parameter specified in the path as their respective keys.

To use the dynamic routes, we should provide different types of routes. Using dynamic routes allows us to
pass parameters and process based on them.

Here is an example of a dynamic route:

var express = require('express');


var app = express();
app.get('/:id', function(req, res){
res.send('The id you specified is ' + req.params.id);
});
app.listen(3000);

To test this go to http://localhost:3000/123. The following response will be displayed.

You can replace '123' in the URL with anything else and the change will reflect in the response.

A more complex example of the above is:

var express = require('express');


var app = express();
app.get('/things/:name/:id', function(req, res){
res.send('id: ' + req.params.id + ' and name: ' + req.params.name);
});
app.listen(3000);

To test the above code, go to http://localhost:3000/things/practice/12345.

You can use the req.params object to access all the parameters you pass in the url. Note

To define routes with route parameters, simply specify the route parameters in the path of the route as
shown below.

var expr = require("express");


var app = expr();
app.get('/user/:userId/test/:test', (req, res) => {
req.params;
res.send(req.params);
});
app.listen(5000)

Output: { "userId": "342", "test": "889" }

Route path: /user/:userId/test/:test


Request URL: http://localhost:5000/user/342/test/889
req.params: { "userId": "342", "test": "889" }

app.use()
function is used to mount the specified middleware function(s) at the path which is being specified. It is
mostly used to set up middleware for your application.
Syntax:
app.use(path, callback)
Parameters:
• path: It is the path for which the middleware function is being called. It can be a string representing
a path or path pattern or a regular expression pattern to match the paths.
• callback: It is a middleware function or a series/array of middleware functions.

Sending a response
How to send a response back to the client using Express

Response.send() method is used to send a simple string as a response, and to close the connection:

(req, res) => res.send('Hello World!')

If you pass in a string, it sets the Content-Type header to text/html .

if you pass in an object or an array, it sets the application/json Content-Type header, and
parses that parameter into JSON.

send() automatically sets the Content-Length HTTP response header.

send() also automatically closes the connection.

Use end() to send an empty response .An alternative way to send the response, without any body, it's by
using the Response.end()

method:

res.end()

Sending a JSON response


When you listen for connections on a route in Express, the callback function will be invoked on

every network call with a Request object instance and a Response object instance.

Example:

app.get('/', (req, res) => res.send('Hello World!'))

Here we used the Response.send() method, which accepts any string.

You can send JSON to the client by using Response.json() , a useful method.

It accepts an object or array, and converts it to JSON before sending it:

res.json({ username: 'Flavio' })

We can define a JSON object and directly pass it inside res.send(). For this, JSON.stringify() method
is not required. To send JSON object in res.write(), convert JSON object to string using
JSON.stringify().

Send JSON object using res.write

const expr=require("express")

const app=expr();

student={name:"xyz",age:31}

app.get("/",(req,res)=>{

res.set("content-type", "text/html")

res.write(JSON.stringify(student))

res.send()

})

app.listen(5000);
Send JSON object using res.send

const expr=require("express")

const app=expr();

student={name:"xyz",age:31}

app.get("/",(req,res)=>{

res.set("content-type","text/html")

res.send(student) //res.send automatically converts data in string format

})

app.listen(5000);

Example : Write Express JS script to request server to display json object values on
browser.
const expr=require("express")
const app=expr();
student={name:"xyz",age:31} //JSON OBJECT
app.get("/",(req,res)=>{
res.write( student.name +"\n" + JSON.stringify(student.age)) //student age must be converted to
string type before sending to server

res.send()
})
app.listen(5000)

Example : Write Express JS script to request server to display json object (Array of
Objects) in table form on browser.

const expr=require("express")

const app=expr();

student={

A1:[{name:"xyz",id:1},

{name:"pqr",id:2},

{name:"mnc",id:3},

{name:"abc",id:4}, ]}

app.get("/student",(req,res)=>{
res.set("content-type","text/html")

res.write("<center><table cellspacing='5px' cellpadding='8px' border='1px


solid'><tr><th>Name</th><th>ID</th></tr>")

for(i of student.A1){

res.write("<tr><td>" + i.name + "</td>")

res.write("<td>" + JSON.stringify(i.id) + "</td></tr>")

res.write("</table></center>")

res.send()

}).listen(5000);

Example:
Write an express js script to define one JSON array of 3 objects having properties
name and age. Short these objects according to age. If user request sortednames
in url then all names along with age should be printed according to descending
order of age. Also, display these sorted values on “Sort page” and display JSON
object on “Home page”
const expr = require("express")
const app = expr();
student = [{name:"abc",age:28},
{name:"def",age:40},
{name:"xyz",age:10}]
app.get ("/",(req,res)=>{
res.set ("content-type","text/html")
res.send (student)
})
app.get ("/sortednames ",(req,res)=>{
res.set ("content-type","text/html")
for (i=0;i<student.length;i++){
for (j=0;j<student.length;j++){
if (student[i].age>student[j].age){
temp = student[i];
student [i] = student[j];
student [j] = temp
}
}
}
for (k=0;k<student.length;k++){
res.write ("<center><h2>"+student[k].name+ " = " +student[k].age +"</h2></center>")
}
res.send ()
})
app.listen (5200)

Serving Static Files(HTML,CSS,Javascript,image


files)
Express provides a built-in middleware express.static to serve static files, such as
HTML,images, CSS, JavaScript, etc.
You simply need to pass the name of the directory where you keep your static assets, to
the express.static middleware to start serving the files directly. For example, if you keep
your images, CSS, and JavaScript files in a directory named public, you can do this −
app.use(express.static('public'));
We will keep a few images and HTML file in public sub-directory as follows −

var express = require('express');


var app = express();

app.use(express.static('public'));

app.get('/', function (req, res) {


res.send();
})

app.listen(8081, function () {

console.log("server start")
})
Save the above code in a file named app.js and run it with the following command.
$ node app.js
Now open localhost:8081/img1.png in any browser and see observe following result.
Create one folder for public and one folder src
Suppose, here we have created folder named public to create HTML, CSS file inside it and src
folder to create JS files inside it. So, we can manage the files easily.
Inside Folder public >> Create one HTML file named index.html and CSS file named express.css”

/public/index.html
<html>
<head>
<title> Website</title>
<link href="express.css" rel="stylesheet"/>
</head>
<body>

<form action="get">
<fieldset>
<legend>Sign-up</legend>
Username: <input type="text" name="username"/>
</br></br>
password: <input type="text" name="password"/>
<br></br>
<textarea rows="5" cols="10" name="ta">

</textarea>
<br></br>
<input type="submit"/>
</fieldset>
</form>
</body></html>
/public/express.css
h1{
font-style:italic;
text-align:center;
text-decoration:line-through;
color:white;
background-color: red;
}
p{
border: 1px solid black;
text-align: justify;
text-transform: capitalize;
color: blue;
}

/src/app.js

const expr=require("express");
const path=require("path");
const app=expr();
const staticPath=path.join(__dirname,"../Public");
console.log(staticPath);
app.use(expr.static(staticPath));
app.listen(5004,()=>
{
console.log("server running");
});

Create one.html file and app.js file. If Both this files are in same folder then res.sendFile( ) function
is used to display one.html on browser.

One.html

<html>
<head>
<title> Website</title>
</head>
<body>

<form method="get">
<fieldset>
<legend>Sign-up</legend>
Username: <input type="text" name="uname"/>
</br></br>
password: <input type="text" name="pwd"/>
<br></br>

<input type="submit"/>
</fieldset>
</form>
</body>
</html>
App.js

const expr=require("express");
const path=require("path");
const app=expr();
const staticPath=path.join(__dirname);
console.log(staticPath);
app.use(expr.static(staticPath));
app.get("/",(req,res)=>
{
res.sendFile("/one.html");
})
app.listen(5004,()=>
{
console.log("server running");
});

HTTP methods
GET and POST both are two common HTTP requests used for building REST API's. GET requests are used to
send only limited amount of data because data is sent into header while POST requests are used to send
large amount of data because data is sent in the body.

Express.js facilitates you to handle GET and POST requests using the instance of express.

GET Method
It facilitates you to send only limited amount of data because data is sent in the header. It is not secure
because data is visible in URL bar.

EXAMPLE

Write express script to get form data using get method and display data in JSON format in next
page named “process_get”

Solution: create two file in same folder (index.html and app.js)

index.html

<html>
<body>
<form action=" /process_get" method="GET">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>

app.js

var express = require('express');


var app = express();
app.get('/', function (req, res) {
res.sendFile( __dirname + "/index.html" );
})
app.get('/process_get', function (req, res) {
response = {
first_name:req.query.first_name,
last_name:req.query.last_name
};
res.send(response);
})
app.listen(8000)
OR

Solution: create two file in different folder (public/index.html and src/app.js)

public/index.html

<html>
<body>
<form action=" /process_get" method="GET">
First Name: <input type="text" name="first_name"> <br>
Last Name: <input type="text" name="last_name">
<input type="submit" value="Submit">
</form>
</body>
</html>
Src/app.js

const expr=require("express");
const path=require("path");
const app=expr();
const staticpath=path.join(__dirname,"../public");
console.log(staticpath);
app.use(expr.static(staticpath));
app.get("/process_get",(req,res)=>
{
const response=
{
fname:req.query.firstname,
lname:req.query.lastname
};
console.log(response);
res.end(JSON.stringify(response));
});

app.listen(5000,()=>
{
console.log("server starte");
});

To run : > node app.js

On browser: localhost:5000/

Above code will automatically open index.html file on browser

If you want to open html file with other name like second.html then write below code.

Here second.html file is in public folder and app.js is in src folder

app.js

const expr=require("express");
const path=require("path");
const app=expr();
const staticpath=path.join(__dirname,"../public");
console.log(staticpath);
app.use(expr.static(staticpath,{index:"second.html"}));
app.get("/process_get",(req,res)=>
{
const response=
{
fname:req.query.firstname,// req.query will give querystring from URL
lname:req.query.lastname
};
console.log(response);
res.end(JSON.stringify(response));
});

app.listen(5000,()=>
{
console.log("server starte");
});

Program:
Write express js script to print message in next line splitting by “,” And use get method to submit
the data. HTML file contains form of text area for the message and submit button.

src/app.js

const expr=require("express");
const path=require("path");
const app=expr();
const staticpath=path.join(__dirname);
console.log(staticpath);
app.use(expr.static(staticpath,{index:"third.html"}));
app.get("/process_get",(req,res)=>
{ res.set("content-type","text/html");
data=req.query.textarea1
console.log(data);
a=data.split(',');
for(x in a)
{res.write(a[x]+"<br>");
}
res.end();
});
app.listen(2501,()=>
{
console.log("server starte");
});

src/third.html

<html>
<head>

</head>
<body>
<form action="/process_get" method="get">
<textarea row="5" cols="15" name="textarea1"> this is an textarea tag,
we are doing express js,this is demo</textarea>
<input type="submit"/>
</form>

</body>
</html>

Post Method
The most common way to send diverse and large amounts of data via HTTP is to use
the POST method.

Before we can easily access this data on the server side in Express, we need to
use some middleware, like the body-parser package

body-parser package, to parse the data in to a format that we can easily access.

Express has a module body-parser that includes a parser for URL-encoded request
bodies, like the ones submitted by HTML forms.

Example:

const expr=require("express");
const app=expr();
const bp=require("body-parser");
const url=bp.urlencoded({extended:true});
const staticpath=__dirname;
app.use(expr.static(staticpath));
app.post("/process_post",url,(req,res)=>
{
res.write(`<h1 style="color:red">username:${req.body.firstname}</h1>`)
res.write(`<h1 style="color:yellow">username:${req.body.lastname}</h1>
<h1>gender=${req.body.a1}</h1>`);

res.end();

}
);
app.listen(5000,()=>
{
console.log("server start");
});
index.html

<html>
<head>
<link href="new.css" rel="stylesheet"/>
</head>
<body>
<h1>this is a demo</h1>
<form action="/process_post" method="post">
<input type="text" name="firstname"/>
<input type="text" name="lastname"/>

<input type="radio" name="a1" value="male"/>MAle


<input type="radio" name="a1" value="female"/>FEMAle
<input type="submit"/>
</form>
</body>
</html>

New.css

h1
{
text-align:center;
color:red;
text-transform:uppercase;
background-color:black;
}

Program:
Write express js script to perform tasks as asked below.

1. Create one HTML file which contains two number type input fields, one dropdown which contains
options like (select, addition, subtraction, multiplication, division) and one submit button.
2. The input fields must contain the value greater than 0 else it will give a message “Please enter
the valid message”. Also, user must select any of the formula from the dropdown else give a
message “You have not selected any formula”. (Message will be displayed on “/calc” page.)
3. If one formula is selected and numbers are entered then respective calculations will be
performed on the page “/calc”.
4. Use post method to request data.

App.js

var expr = require("express");


var app = expr();
var p = require("path");
const bp=require("body-parser");
const url=bp.urlencoded({extended:true});
const staticpath = p.join(__dirname,"../public");
app.use(expr.static(staticpath,{index:'calculate.html'}));

app.post("/calc",url,(req,res)=>{
res.set("content-type","text/html");
var n1 = parseInt(req.body.n1);
var n2 = parseInt(req.body.n2);
if ((n1>0) && (n2>0)) {
if(req.body.formula == "addition"){
a = n1+n2;
res.write("<h1>Addition is : " + a + "</h1>");
}
else if(req.body.formula == "subtraction"){
s = n1-n2;
res.write("<h1>Subtraction is : " + s + "</h1>");
}
else if(req.body.formula == "multi"){
m = n1*n2;
res.write("<h1>Multiplication is : " + m + "</h1>");
}
else if(req.body.formula == "div"){
d = n1/n2;
res.write("<h1>Division is : " + d + "</h1>");
}
else{
res.write("<h1>You have not selected any formula.</h1>");
}
}else{
res.write("<h1>Please enter the valid number/s.</h1>");
}
res.send()
})

app.listen(5000);

calculate.html

<html>
<body>
<form action="/calc" method="post">
<fieldset>
<legend>Calculator:</legend>
<label for="n1">Enter Number1:</label>
<input type="number" name="n1"><br><br>

<label for="n2">Enter Number2:</label>


<input type="number" name="n2"><br><br>

<label for="formula">Formula: </label>


<select name="formula" id="formula">
<option value="">Select formula</option>
<option value="addition">Addition</option>
<option value="subtraction">Subtraction</option>
<option value="multi">Multiplication</option>
<option value="div">Division</option>
</select><br><br>

<input type="submit" value="Submit">


</fieldset>
</form>
</body>
</html>

Middleware
Express.js is a routing and Middleware framework for handling the different routing
of the webpage and it works between the request and response cycle.

Middleware gets executed after the server receives the request and before the
controller actions send the response.

Advantages of using middleware:


• Middleware can process request objects multiple times before the server works
for that request.
• Middleware can be used to add logging and authentication functionality.
• Middleware improves client-side rendering performance.
• Middleware is used for setting some specific HTTP headers.
• Middleware helps for Optimization and better performance.

Middleware Chaining: Middleware can be chained from one to another, Hence


creating a chain of functions that are executed in order. The last function sends
the response back to the browser. So, before sending the response back to the
browser the different middleware process the request.
The next() function in the express is responsible for calling the next middleware
function

Modified requests will be available to each middleware via the next function –

Middleware Syntax:
app.get(path, (req, res, next) => {})
Middleware functions take 3 arguments: the request object, the response object,
and the next function in the application’s request-response cycle, i.e., two
objects and one function.

Example:

const expr=require("express");
const app=expr();
const path=__dirname;
app.use((req,res,next)=>
{
console.log("initialize");
res.write("hello1");
next();
});
app.get("/",(req,res)=>
{
res.write("hello2");
res.send();
});
app.listen(5001,()=>
{
console.log("server start");
});
Example:

const expr=require("express");
const app=expr();

app.get("/hello",(req,res,next)=>
{

res.write("request received on"+ new Date());


next();
});
app.get("/hello",(req,res,next)=>
{
console.log("hello1");
next();

});
app.get("/hello",(req,res)=>
{
res.send();

}).listen(5000);

Program:

Write express js script to perform following tasks.

1. Create one html file which contains one text field for name, email field and checkbox for
subscription. Html file will be loaded on home page. Email and name fields are required fields.
2. On login page welcome user and email id data should be printed.
a. If user checked the subscription then “Thank you for the subscription” message will be
printed and “logout” link will be displayed under the message. If user clicks logout link
then he/she will be redirected to the home page.
b. If user has not opted for the subscription then “You can subscribe to get daily updates”
message will be printed and “subscribe” link will be displayed under the message. If user
clicks subscribe link then he/she will be redirected to the subscription page. In this page
“Thank you for the subscription” message will be printed and “logout” link will be
displayed under the message. If user clicks logout link then he/she will be redirected to
the home page.

Use concept of the middleware and you can use any of http methods(get/post).

src/app.js

var expr = require("express");


var app = expr();
var p = require("path");
const staticp = p.join(__dirname,"../public");
app.use(expr.static(staticp,{index:'home.html'}));
app.get("/login",(req,res,next)=>{
console.log(req.query);
res.set("content-type","text/html");
res.write("<center><h1>Welcome " + req.query.name + "</h1>");
res.write("<center><h2>Your email id is " + req.query.email + "</h2>");
next();
})
app.get("/login",(req,res,next)=>{
if(req.query.newsletter == "on"){
res.write("<h3>Thank you for your subcsription</h3><a href='/'>Logout</a>");
}else{
res.write("<h3>You can subcribe to get daily updates</h3><a href='/subscribe'>Subscribe</a></center>");
}
next();
});
app.get("/subscribe",(req,res)=>{
res.set("content-type","text/html");
res.write("<h3>Thank you for your subcsription</h3></center><a href='/'>Logout</a>");
res.send();
});

app.listen(5001);

/public/home.html

<form action="/login" method="get">


<label for="name">Name:</label>
<input type="text" name="name" required><br><br>

<label for="email">Email:</label>
<input type="email" name="email" required><br><br>

<input type="checkbox" name="newsletter" id="newsletter">


<label for="newsletter">Subscribe?</label><br><br>

<input type="submit" value="Submit">


</form>
Program(QB-120)
write an express.js script to load an HTML file having username and password and submit
button. On clicking submit button. It should jump on "check" page using "POST" method. If
username is "admin" , then jump on next middleware to print "welcome… admin" , if username
is not "admin" , then stay on same middleware to print "warning msg" in red color.
Index.html

<html>
<body>
<form action ="/check" method="post">
Username: <input type="text" name="uname"/>
</br></br>
password: <input type="text" name="pwd"/>
<br></br>
<input type="submit"/>
</form>
</body>
</html>

App.js

const expr=require("express");
const app=expr();
const bp=require("body-parser");
const url=bp.urlencoded(
{
extended:false
});
console.log(url);
const staticPath=__dirname;
app.use(expr.static(staticPath));
app.post("/check",url,(req,res,next)=>
{ if(req.body.uname=="admin")
{
next();
}

else{
res.send("<h1 style='color:red'>wrong credentials</h1>")
}
});
app.post("/check",url,(req,res,next)=>
{
res.write(`<h1>welcome...${ req.body.uname}</h1>`)
res.send();
}
).listen(3001);

Cookies
Cookies are simple files that are stored on user’s computer. It stores the data in
a text file. This helps us to keep track of the user action. Cookies can be accessed
either by the web server or client computer. This allows the server to deliver a
page to a particular user, or the page itself can be stored some script which is
aware of the data in the cookie and so is able to carry information from one visit
to the website or related site to the next.

What’s in a cookie?
Each cookie is finally small lookup table involves pairs of key-values – for example
(first name, Steve) (last name, jobs). Once the cookie has been read by the code on
server or client computer, the data can be restored and used to customize the web
page accordingly.

Why are Cookies Used?


Cookies are an adequate way to carry data between sessions on a website, without
loading a server machine with huge amounts of data storage. If we store data on a
server without cookies it would be insecure and inconvenient because then it will
get difficult to restore users data without requiring a login on each visit to the
website.
Installation:-
To use cookies with express, firstly we have to install cookie-parser middleware.
To install it, use the following command-

npm install cookie-parser

Now to use cookies with express, we will have to require the cookie-parser module.
Cookie-parser is a middleware which parses cookies to attach with the client
request object.

var cookieparser = require(‘cookie-parser’);


app.use(cookieparser());

Adding cookies

To use a new cookie, first define a new route in your express.js app like:-

var express = require('express');


var app = express();
var cookieParser = require('cookie-parser');
app.use(cookieParser());
app.get('/', function(req, res) {
res.cookie('mycookies', 'express')
res.send('cookie set');
});
app.listen(3000, function(err, message) {
console.log("server start......")
});

Browser always sends back cookies every time it queries the server.

Display cookie
To view cookies from your server req.cookies function is used. add the following
console to that route.

console.log(‘cookies:’ ,req.cookies)
How Long Does a Cookie Store?
The time of expiry of a cookie can be set when the cookie is created. If time is
not set by the user then by default, the cookie is destroyed when the current
browser window is closed.

Adding Cookies with Expiration Time:-


You can add cookies that expire. Just pass an object with property ‘expire’ and
set to the time when you want it to expire from your browser. Following is an
example of this method.

//Expires after 360000 ms from the time it is set.


res.cookie(name, 'value', {expires:new Date(Date.now()+1000)});

The other way to set the expiration time is using ‘maxAge’ property. Following is
an example of this method.

//This cookie also expires after 360000 ms from the time it is set.
res.cookie(name, 'value', {maxAge: 360000});

Delete existing cookies:-

To delete a cookie, use the clearCookie function.

res.clearCookie('mycookies');

Example:

const expr=require("express");
const app=expr();
const cp=require("cookie-parser");
app.use(cp());
app.get("/",(req,res,next)=>
{
res.cookie("fname","xyz");
res.cookie("lname","pqr");
next();
});
app.get("/",(req,res,next)=>
{
console.log(req.cookies);
next();
});
app.get("/",(req,res)=>
{
res.clearCookie("fname");
res.send("cookie deleted");
});
app.listen(5001,()=>
{
console.log("listen on 5001");
}
);

Example:

const expr=require("express");
const app=expr();
const cp=require("cookie-parser");
app.use(cp());

app.get("/",(req,res,next)=>
{
res.cookie("uname","xyz",{
expires:new Date(Date.now()+20000)
});
res.cookie("lname","xyz1",{
expires:new Date(Date.now()+10000)
});
res.cookie("abc","pqr");
next();
});
app.get("/",(req,res,next)=>
{
console.log(req.cookies.uname);
next();
//res.send()
});
app.get("/",(req,res)=>
{
res.clearCookie("uname");
res.send("Cookie deleted");
});
app.listen(8001,()=>
{
console.log("server running at 8001");
});
Program:
write a script to create a login form on index.html file. After
clicking submit button it should jump to /next page and value of
username should be stored inside cookie. perform the task using get
method. observe and check inside browser that the cookie is stored
perfectly or not.
index.html

<html>
<body>

<form action="/next" method="get">


<fieldset>
<legend>Sign-up</legend>
Username: <input type="text" name="uname"/>
</br>
password: <input type="text" name="pwd"/>
<br>

<input type="submit"/>
</fieldset>
</form>
</body>
</html>

App.js

var expr=require("express")

var cp=require("cookie-parser")
var app=expr()
app.use(cp())
app.get("/",(req,res)=>{
res.sendFile(__dirname+"/index.html")})
app.get("/next",(req,res,next)=>{
const response={
u:req.query.uname,
p:req.query.pwd
}
res.cookie("uname",response.u)
next()
})
app.get("/next",(req,res)=>{
console.log(req.cookies)
res.send(req.cookies)
})
app.listen(3000)
Program:

You have been assigned to develop a user feedback form for a website
using Express.js and cookies. Implement the following requirements:
Create a form with the following fields:
Name (input field)
Email (input field)
Message (textarea field)
Rating (radio buttons: Bad, Average, Good, Very Good, Excellent)
When the user submits the form, store their feedback information (name,
email, message, and rating) in a cookie named "feedback" that expires
in 10 seconds.
Display a confirmation message to the user after successfully
submitting the form & Create a link to display the feedback details
stored in the "feedback" cookie.
When the user click to the link, retrieve the feedback information from
the cookie and display it on the page also include a link on the
feedback details page to Logout.When the user clicks the link, user
redirected to home page.
Make simple.html file and app.js file use get method in express js.

Simple.html
<html>
<head>
<title>User Feedback Form</title>
</head>
<body>
<h1>User Feedback Form</h1>
<form action="/submit-feedback" method="get">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required><br><br>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required><br><br>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea><br><br>
<label for="rating">Rating:</label>
<input type="radio" id="rating1" name="rating" value="Bad" required>
<label for="rating1">Bad</label>
<input type="radio" id="rating2" name="rating" value="Average" required>
<label for="rating2">Average</label>
<input type="radio" id="rating3" name="rating" value="Good" required>
<label for="rating3">Good</label>
<input type="radio" id="rating4" name="rating" value="Very Good" required>
<label for="rating4">Very Good</label>
<input type="radio" id="rating5" name="rating" value="Excellent" required>
<label for="rating5">Excellent</label><br><br>
<input type="submit" value="Submit">
</form>
</body>
</html>

App.js
const express = require('express');
const cp = require('cookie-parser');
const app = express();
app.use(cp());
app.get('/', (req, res) => {
res.sendFile(__dirname + '/simple.html');
});
app.get('/submit-feedback', (req, res) => {
const { name, email, message, rating } = req.query;

// Create the feedback object


const feedback = {
name,
email,
message,
rating
};
// Set the feedback cookie with a 10-second expiration
res.cookie('feedback', feedback, { maxAge: 10000 });
res.send('Thank you for your feedback! <br> <a href="/feedback-details"> Show
Feedback </a>');
});

app.get('/feedback-details', (req, res) => {


const feedback = req.cookies.feedback;

if (feedback) {
res.send(`
<h1>Feedback Details</h1>
<p><strong>Name:</strong> ${feedback.name}</p>
<p><strong>Email:</strong> ${feedback.email}</p>
<p><strong>Message:</strong> ${feedback.message}</p>
<p><strong>Rating:</strong> ${feedback.rating}</p>
<a href="/" > logout </a>`);
}
else {
res.send('No feedback available.');
}
});

app.listen(5000, () => {
console.log('Server is running on port 5000');
});
Session
A website is based on the HTTP protocol. HTTP is a stateless protocol which means
at the end of every request and response cycle, the client and the server forget
about each other.

This is where the session comes in. A session will contain some unique data about
that client to allow the server to keep track of the user’s state.

In session-based authentication, the user’s state is stored in the server’s memory


or a database.

How sessions works


When the client makes a login request to the server, the server will create a
session and store it on the server-side.

When the server responds to the client, it sends a cookie. This cookie will
contain the session’s unique id stored on the server, which will now be stored on
the client.

This cookie will be sent on every request to the server.

Why Use Sessions?


Sessions are used to store information such as User ID over the server more
securely, where it cannot be altered. This prevents the information from being
tampered with.

In addition to this, sessions can transfer the information from one web page to
another in the form of value.
The difference between session and cookie

Basis of Cookie Session


Comparison

Cookies are client-side Sessions are server-side files that


files that are stored on store user information.
Definition
a local computer and
contain user information.

Cookies expire after the The session ends when the user closes
Expiry user specified lifetime. the browser or logs out of the
program.

It can only store a It is able to store an unlimited


Data storage
limited amount of data. amount of information.

Cookies can only store up There is a maximum memory restriction


to a maximum of 4 KB of of 128 megabytes that a script may
Capacity data in a browser. consume at one time. However, we are
free to maintain as much data as we
like within a session.

Cookies are used to store The data is saved in an encrypted


Data Format information in a text format during sessions.
file.

Installation
Installation is done using the npm install command:
npm install express-session

require express-session module


var session = require('express-session')

To set up the session, you need to set a couple of Express-session options, as shown below.

app.use(session(
{
resave:false,// Do not save session if not modify
saveUninitialized:false,// Do not create session if something is not
stored
secret:"Hello"
}
));

resave: It basically means that for every request to the server, it reset the session cookie. Even if the
request was from the same user or browser and the session was never modified during the request.

saveUninitialized: When an empty session object is created and no properties are set, it is the
uninitialized state. So, setting saveUninitialized to false will not save the session if it is not modified.

Secret: is a random unique string key used to authenticate a session. secret parameter allows
express-session to use it to encrypt the session-Id

Example:

const expr=require("express");
const app=expr();
const sess=require("express-session");
app.use(sess(
{
resave:true,
saveUninitialized:true,
secret:"Hello"
}
));
app.get("/",(req,res)=>
{
if(!req.session.fname)
{ req.session.fname="hiral"
res.redirect("/fetchsession")
}
else
{
console.log("Session is already set...");
}
})
app.get("/fetchsession",(req,res)=>
{

res.write(`<h1> Welcome... ${req.session.fname} <h1>`);


res.write(`<button><a href="deletesession">Delete session</a></button>`);
res.send();
})
app.get("/deletesession",(req,res)=>
{
req.session.destroy();
res.send("Session destroy")
})
app.listen(8004,()=>
{
console.log("server running at 8004");
});

Program(QB-121): write a script to meet following requirements.

1) create index.html page and open it on localhost


2) after clicking submit button, it should jump to savesession page. store username in session.
3) After saving session, redirect to fetchsession page and read session value. put a logout link
button here.
4) destroy the session on this page and redirect to index.html
index.html

<html>
<head>
<title> Website</title>
</head>
<body>

<form action="/savesession" method="get">


<fieldset>
<legend>Sign-up</legend>
Username: <input type="text" name="uname"/>
</br>
password: <input type="text" name="pwd"/>
<br>

<input type="submit"/>
</fieldset>
</form>
</body>
</html>

App.js

const expr=require("express");
const app=expr();
const sess=require("express-session");
app.use(expr.static(__dirname,{index:"sessiontask.html"}))
app.use(sess(
{
resave:true,
saveUninitialized:true,
secret:"Heloo"
}
));

app.get("/savesession",(req,res)=>
{
if(!req.session.u)
{ req.session.u=req.query.uname
res.redirect("/fetchsession")
}
else
{
console.log("Session is already set...");
}
})
app.get("/fetchsession",(req,res)=>
{

res.write(`<h1 style="color:blue;border:5px solid black;font-style:italic">


Welcome... ${req.session.u} <h1>`);
res.write(`<button><a href="deletesession">Logout</a></button>`);
res.send();
})
app.get("/deletesession",(req,res)=>
{
req.session.destroy();
res.redirect("/")

})
app.listen(8004,()=>
{
console.log("server running at 8001");
});

Example :

write express script to print how much time user visit the page. For ex., if user visit first time
,”you have visited page First time” message will print. if user visit second time ,”you have visited
page second time” message will print. and so on.

const expr=require("express");
const app=expr();
const sess=require("express-session");
app.use(sess(
{
resave:true,
saveUninitialized:true,
secret:"Helo1"
}
));

app.get("/",(req,res)=>
{
if(req.session.page_views)
{
req.session.page_views++;
res.send(`<h1 style="color:blue;border:5px solid black;font-style:italic">
You have visited page ${req.session.page_views} times <h1>`);
}
else{
req.session.page_views=1,
res.send(`<h1 style="color:green;border:5px solid black;font-
style:italic"> Welcome.. You have visited page ${req.session.page_views}
times<h1>`);
}

});

app.listen(8001,()=>
{
console.log("server running at 8001");
});

You might also like