Express Unit 4
Express Unit 4
Introduction
Express.js is a small framework that works on top of Node.js web server functionality to
simplify its APIs and add helpful new features.
It makes it easier to organize your application’s functionality with middleware and routing.
It adds helpful utilities to Node.js HTTP objects and facilitates the rendering of dynamic HTTP
objects.
Features of Express JS
Develops Node.js web applications quickly and easily.
It’s simple to set up and personalize.
Allows you to define application routes using HTTP methods and URLs.
Includes a number of middleware modules that can be used to execute additional requests
and responses activities.
Simple to interface with a variety of template engines, including pug(Jade), Vash, and EJS.
Allows you to specify a middleware for handling errors.
Environment Setup
Node Package Manager(npm)
npm is the package manager for node.
The npm Registry is a public collection of packages of open-source code for Node.js, front-
end web apps, mobile apps, robots, routers, and countless other needs of the JavaScript
community.
npm allows us to access all these packages and install them locally. You can browse through
the list of packages available on npm at npmJS.
P a g e 1 | 50
Chapter 4 Express JS
Locally − This method is generally used to install frameworks and libraries. A locally
installed package can be used only within the directory it is installed. To install a package
locally, use the same command as above without the -g flag.
P a g e 2 | 50
Chapter 4 Express JS
Step 3 − Now we have our package.json file set up, we will further install Express. To install
Express and add it to our package.json file, use the following command −
npm install express --save
The --save flag can be replaced by the -S flag. This flag ensures that Express is added as a
dependency to our package.json file. This has an advantage, the next time we need to install all
the dependencies of our project we can just run the command npm install and it will find the
dependencies in this file and install them for us.
We can also install express by below command.
npm install express
OR
npm i express
To check version of express run below command or you can check in package.json file.
npm list express
P a g e 3 | 50
Chapter 4 Express JS
Index.js
var express = require('express');
var app = express();
app.get('/', function(req, res){
res.set ("content-type","text/plain");
res.send("Hello world!");
});
app.listen(3000);
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.
P a g e 4 | 50
Chapter 4 Express JS
res.set()
The res.set() function is used to set the response HTTP header field to value. To set multiple
fields at once, pass an object as the parameter.
res.set(field [, value])
Parameters: The field parameter is the name of the field and the value parameter is the value
assigned to the field parameter.
app.get(route, callback)
This function tells what to do when a get request at the given route is called. The callback
function has 2 parameters, request(req) and response(res).
The request object(req) represents the HTTP request and has properties for the request
query string, parameters, body, HTTP headers, etc. Similarly, the response object represents
the HTTP response that the Express app sends when it receives an HTTP request.
res.send()
This function takes an object as input and it sends this to the requesting client. Here we are
sending the string "Hello World!".
1 port
A port number on which the server should accept incoming requests.
P a g e 5 | 50
Chapter 4 Express JS
2 host
Name of the domain. You need to set it when you deploy your apps to the cloud.
3 backlog
The maximum number of queued pending connections. The default is 511.
4 callback
An asynchronous function that is called when the server starts listening for
requests.
Response methods
The methods on the response object (res) in the following table can send a response to the
client, and terminate the request-response cycle.
Method Description
res.end: comes from NodeJS core. In Express JS if you need to end request in a quick way
and do not need to send any data then you can use this function.
res.send: Sends data and end the request.
res.json: Sends data in JSON format and ends the request.
res.json() allows for extra formatting of the JSON data - if this is not required res.send() can
also be used to return a response object using Express. Both of these methods also end the
response correctly, and there's no further action required.
Just for the information
In Node JS we learnt http module.
var http=require("http");
P a g e 6 | 50
Chapter 4 Express JS
var server=http.createServer(
function(req,res){
if(req.url=="/")
{
res.writeHead(200,{"content-type":"application/json"});
res.write("<h1>Thank you..!</h1>");
res.end();
}
});
server.listen(6001);
P a g e 7 | 50
Chapter 4 Express JS
Example
1.js Output
const express = require("express"); In terminal > node 1.js
const app = express(); Console >>
app.get ("/", (req,res)=> server started
{ In browser >>
res.set ("content-type","text/plain"); localhost:5504
res.send ("<h1>Hello</h1>"); <h1>Hello</h1>
}); localhost:5504/about
app.get ("/about", (req,res)=> Hello
{ Note: Like node JS we cannot set
res.set ("content-type","text/html"); headers after they are sent to the
res.write ("Hello"); client. Means if we send response
res.send ("<h1> Hello from by writing in “res.write()” then
home</h1>"); “res.send()” must be blank.
//res.write ("hello");
}); Here in example on about page
app.listen (5504,()=> only hello will be displayed. And in
{ console it will give an error
console.log ("server started"); “Cannot set headers after they are
}) sent to the client”. Means we
cannot write anything in
res.send().
P a g e 8 | 50
Chapter 4 Express JS
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.
The main difference between a URL and a URI is that a URL specifies the location of a resource
on the internet, while a URI can be used to identify any type of resource, not just those on the
internet.
Route definition takes the following structure:
app.METHOD(PATH, HANDLER)
Respond to POST request on the root route (/), the application’s home page:
app.post('/', (req, res) => {
res.send('Got a POST request')
})
P a g e 9 | 50
Chapter 4 Express JS
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.
Route path: /calendar/:day/event/:ename
Request URL: http://localhost:6001/calendar/monday/event/birthday
req.params: {"day":"monday","ename":"birthday"}
To define routes with route parameters, simply specify the route parameters in the path of
the route as shown below.
var express = require("express");
var app = express();
app.get('/calendar/:day/event/:ename', (req, res) => {
res.send(req.params);
});
app.listen (6001,()=>
{
console.log ("server started");
})
To check: http://localhost:6001/calendar/monday/event/birthday
Output:
{"day":"monday","ename":"birthday"}
P a g e 10 | 50
Chapter 4 Express JS
JSON Processing
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().
Write express script to send json object to server and display it.
Send JSON object using res.json
const express=require("express")
const app=express();
student={name:"LJU",age:28}
app.get("/",(req,res)=>{
res.json(student)
})
app.listen(6007)
Output in browser: {"name":"LJU","age":28}
P a g e 11 | 50
Chapter 4 Express JS
Example : Write Express JS script to request server to display only Age on browser.
const express=require("express")
const app=express();
student={name:"LJU",age:28}
app.get("/",(req,res)=>{
res.write(student.age+"") //needs to convert to string so appended string
res.send()
})
app.get("/j",(req,res)=>{
res.send(student.age+"") //needs to convert to string so appended string
})
app.get("/j1",(req,res)=>{
res.json(student.age)
})
app.listen(6001)
Example : Write Express JS script to request server to display json object (Array of
Objects) in table form on browser.
const express=require("express") Output:
const app=express();
student={
u1:[{name:"LJU",id:2},
{name:"LJU1",id:3},
{name:"LJU2",id:4},
{name:"LJU3",id:5},
{name:"LJU4",id:6}]}
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.u1){
res.write("<tr><td>" + i.name + "</td>")
res.write("<td>" + JSON.stringify(i.id) +
"</td></tr>")
P a g e 12 | 50
Chapter 4 Express JS
}
res.write("</table></center>")
res.send()
})
app.listen(6007)
Example: Write an express js script to define one JSON array of 3 objects having properties
name and age. Sort this object according to age. If user requests sorted names 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 express = require("express")
const app = express();
student = [{name:"abc",age:28},
{name:"def",age:40},
{name:"xyz",age:50}]
//home page
app.get ("/",(req,res)=>{
res.set ("content-type","text/html")
res.send (student)
})
//sort page
app.get ("/sort",(req,res)=>{
res.set ("content-type","text/html")
var des = student.sort((a,b)=>b.age-a.age)
console.log(des)
for (k=0;k<des.length;k++){
res.write ("<center><h2>"+des[k].name+ " = " +des[k].age +"</h2></center>")
}
res.send ()
})
app.listen (5200)
OR
const express = require("express")
const app = express();
student = [{name:"abc",age:28},
{name:"def",age:30},
P a g e 13 | 50
Chapter 4 Express JS
{name:"xyz",age:50}]
//home page
app.get ("/",(req,res)=>{
res.set ("content-type","text/html")
res.send (student)
})
//sort page
app.get ("/sort",(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)
Output:
On home page
[{"name":"abc","age":28},{"name":"def","age":40},{"name":"xyz","age":50}]
On sort page
xyz = 50
def = 40
abc = 28
P a g e 14 | 50
Chapter 4 Express JS
P a g e 15 | 50
Chapter 4 Express JS
Folder structure
express express express express
|-----1.js |---1.js |------backend |-------backend
|-----index.html |-----frontend |--------|--1.js |---------|---1.js
|-----1.css |------|---index.html |---index.html |-------frontend
|-----1.png |------|---1.css |---1.css |---------|---index.html
|------|---1.png |---1.png |---------|---1.css
|---------|---1.png
Here we need to join the
path as we need to go to Here we need to join the
one step up to access path as we need to go to
the frontend files. one step up to access the
frontend files.
Code:
const sp = path.join
Code: Code: Code: (__dirname
app.use app.use const sp = path.join ,"../frontend");
(express.static (express.static (__dirname ,"../"); app.use
(__dirname)); ("frontend")); app.use (express.static (express.static(sp));
(sp));
P a g e 16 | 50
Chapter 4 Express JS
express
|-----1.js
|-----index.html
|-----1.css
Example
/express/index.html /express/1.css /express/1.js
<html> .lj_p { const express = require ("express")
<head><link font-size:100; const app = express();
rel="stylesheet" color:blueviolet; // name of file must be index.html
href="1.css"></head> } app.use(express.static(__dirname))
<body><p class="lj_p"> app.listen (5200)
File name must be
index.html </p>
</body>
</html>
To run in terminal : go to “express” folder by command cd express and then node 1.js
Output in browser:
P a g e 17 | 50
Chapter 4 Express JS
Load HTML file named index.html (create a frontend folder inside express folder and create
index.html and 1.css inside it)
express
|---1.js
|-----frontend
|------|---index.html
|------|---1.css
Example
/express/frontend/index.ht /express/frontend/1.cs /express/1.js
ml s const express = require ("express")
<html> .lj_p { const app = express();
<head> font-size:100; // name of file must be index.html
<link rel="stylesheet" color:blueviolet; app.use(express.static(“frontend”
href="1.css"> } ))
</head> app.listen (5200)
<body>
<p class="lj_p"> File name
must be index.html </p>
</body>
</html>
To run in terminal : go to “express” folder by command cd express and then node 1.js
Output in browser:
P a g e 18 | 50
Chapter 4 Express JS
Load HTML file named index.html (create a frontend folder inside express folder and create
index.html and 1.css inside it. Also, create backend folder and create 1.js file inside it.)
express
|-------backend
|---------|---1.js
|-------frontend
|---------|---index.html
|---------|---1.css
Example
/express/frontend/index.ht /express/frontend/1.cs /express/backend/1.js
ml s const express = require ("express")
<html> .lj_p { const app = express();
<head> font-size:100; const path = require ("path");
<link rel="stylesheet" color:blueviolet; const staticpath = path.join
href="1.css"> } (__dirname, "../frontend");
</head> // name of file must be index.html
<body> app.use(express.static(staticpath
<p class="lj_p"> File name ))
must be index.html </p> app.listen (5200)
</body>
</html>
To run in terminal : go to “backend” folder by command cd backend and then node 1.js
Output in browser:
Note that if you don’t want to use path module to join the path then you can use below
code.
const express = require ("express")
const app = express();
app.use(express.static((__dirname, "../frontend")))
app.listen (5200)
P a g e 19 | 50
Chapter 4 Express JS
Load HTML file named index.html (create index.html and 1.css files inside express folder.
Create backend folder inside express folder and create 1.js file inside backend folder.)
express
|------backend
|--------|--1.js
|---index.html
|---1.css
Example
/express/index.html /express/1.css /express/backend/1.js
<html> .lj_p { const express = require ("express")
<head><link font-size:100; const app = express();
rel="stylesheet" color:blueviolet; const path = require ("path");
href="1.css"></head> } const staticpath = path.join
<body><p class="lj_p"> (__dirname, "../");
File name must be // name of file must be index.html
index.html </p> app.use(express.static(staticpath))
</body> app.listen (5200)
</html>
To run in terminal : go to “backend” folder by command cd backend and then node 1.js
Output in browser:
P a g e 20 | 50
Chapter 4 Express JS
P a g e 21 | 50
Chapter 4 Express JS
Express
|-------js
|---------|---1.js
|-------html
|---------|---1.html
|-------css
|---------|---1.css
|-------image
|---------|--- folderstructure.png
express/js/1.js
const express = require("express");
const app = express();
const path= require("path");
app.use(express.static(css_path))
app.use(express.static(img_path))
app.use(express.static(html_path,{index:"1.html"}))
app.listen(5001,()=>console.log("Started"))
express/html/1.html
<html>
<head>
<link rel="stylesheet" href="1.css">
</head>
<body>
P a g e 22 | 50
Chapter 4 Express JS
express/css/1.css
.lj_p{
font-size: 60px;
color:purple;
text-align: center;
}
img{ width:400px; height:auto;}
P a g e 23 | 50
Chapter 4 Express JS
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 1
Write express script to get form data using get method and display data in JSON
format in next page named “process_get”
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>
example1.js
var express = require('express');
var app = express();
app.use(express.static(__dirname))
app.get('/process_get', function (req, res) {
response = {
fname:req.query.first_name,
lname:req.query.last_name
};
console.log(req.query); //req.query is used to get the submitted data in json object format.
To access particular key value we have to write “req.query.first_name”
res.send(response);
P a g e 24 | 50
Chapter 4 Express JS
})
app.listen(8000)
OR
var express = require('express');
var app = express();
app.use(express.static(__dirname))
app.get('/process_get', function (req, res) {
fname=req.query.first_name;
lname=req.query.last_name
};
console.log(req.query);
res.send(fname);
})
app.listen(8000)
Example 2
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.
2.html
<html>
<head><title>Get Method</title></head>
<body>
<form method="get" action="/login">
<textarea rows="10" cols="10" name="message">Hi.Hello.how are you
</textarea>
<button name="Submit" value="Submit">Submit</button>
</form>
</body>
</html>
P a g e 25 | 50
Chapter 4 Express JS
2.js
var express = require("express");
var app = express();
app.use(express.static(__dirname,{index: '2.html'}));
app.get("/login",(req,res)=>{
res.set("content-type","text/html");
t1 = (req.query.message).split(".");
for(i in t1){
res.write(t1[i]+ "</br>");
}
res.send();
});
app.listen(5122);
Output:
Hi
Hello
how are you
Example 3
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 number”. 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”.
P a g e 26 | 50
Chapter 4 Express JS
app.use(express.static(__dirname,{index:'calc.html'}));
app.get("/calc",(req,res)=>{
res.set("content-type","text/html");
var n1 = parseInt(req.query.n1);
var n2 = parseInt(req.query.n2);
if ((n1>0) && (n2>0)) {
if(req.query.formula == "addition"){
a = n1+n2;
res.write("<h1>Addition is : " + a + "</h1>");
}
else if(req.query.formula == "subtraction"){
s = n1-n2;
res.write("<h1>Subtraction is : " + s + "</h1>");
}
else if(req.query.formula == "multi"){
m = n1*n2;
res.write("<h1>Multiplication is : " + m + "</h1>");
}
else if(req.query.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(6012);
P a g e 27 | 50
Chapter 4 Express JS
calc.html
<html>
<head>
<link rel="stylesheet" href="/t1.css">
</head>
<body>
<form action="/calc" method="get">
<fieldset>
<legend>Calculator:</legend>
<label for="n1">Enter Number1:</label>
<input type="number" name="n1"><br><br>
P a g e 28 | 50
Chapter 4 Express JS
Post method
It facilitates you to send large amount of data because data is sent in the body. Post method is
secure because data is not visible in URL.
Please note that new version of express contains built-in body-parser module. We don’t need
to install it and import it to our program.
We can access it’s functionality by just adding below line to our program.
var express = require("express");
app.use(express.urlencoded());
If above won’t work properly then follow the following steps of installation and importing
module to the program.
Installation
npm install body-parser
API
var bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }));
Body-parser parses is an HTTP request body that usually helps when you need to know more
than just the URL being hit.
It provides four express middleware for parsing JSON, Text, URL-encoded, and raw data sets
over an HTTP request body.
Using body-parser allows you to access req.body from within routes and use that data.
o extended
The extended option allows to choose between parsing the URL-encoded data
with the querystring library (when false) or the qs library (when true).
Default value is true, but using the default has been deprecated.
P a g e 29 | 50
Chapter 4 Express JS
Example 1
Write express script to retrieve form data using post method and display data in
JSON format in next page named “process”
p.html
<html>
<body>
<form action="/process" method="post">
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>
p.js
var express = require('express');
var app = express();
app.use(express.static(__dirname,{index: 'p.html'}));
app.listen(7002)
Example 2
Write express js script to perform the tasks as asked below.
1)Create one HTML file and add one form which contains username, password and
submit button. Data should be submitted by HTTP post method.
2)Submit button is of black color with white text. (External CSS)
P a g e 30 | 50
Chapter 4 Express JS
3)On home page form should be displayed and while submitting the form, on next
page named “/login” if username is admin then it will display “Welcome admin”
else display “Please login with admin name”.
po2.js
var express = require("express");
var app = express();
app.use(express.urlencoded());
app.use(express.static(__dirname,{index: 'po2.html'}));
app.post("/login",(req,res)=>{
if( req.body.uname == 'admin' ){
res.write(“<h1> Welcome “ + req.body.uname + “</h1>”)
}
else{
res.write(`<h1 style="color:red">Please login with admin name</h1>`);
}
res.send();
})
app.listen(5222);
po2.html
<html>
<body>
<form method="post" action="/login">
<div class="lj-div">
<label>User name:</label>
<input type = "text" name="uname" ></input>
</div>
<div class="lj-div">
<label>Password:</label>
<input type = "text" name="password" ></input>
</div>
<button name="Submit" value="Submit">Submit</button>
</form>
</body>
</html>
P a g e 31 | 50
Chapter 4 Express JS
Express 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.
Middleware has the access to the request object, responses object, and next, it can process
the request before the server send a response.
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 if
there is one.
Modified requests will be available to each middleware via the next function –
Middleware chaining example
In this case, the incoming request is
modified and various operations are
performed using several middlewares, and
middleware is chained using the next
function. The router sends the response
back to the browser.
P a g e 32 | 50
Chapter 4 Express JS
//Method 2
app.use(
"/xyz",
(req, res, next) => {
console.log("request received on"+new Date());
next();
},
(req, res, next) => {
res.set("content-type","text/html")
res.write("Hello");
next();
},
(req, res) => {
res.write(`<div>
<h2>Welcome to LJU</h2>
P a g e 33 | 50
Chapter 4 Express JS
<h5>Tutorial on Middleware</h5>
</div>`);
res.send();
}
);
app.listen(6001)
Output:
localhost:6001/ee
On browser
First
Addition = 10
Hello Welcome to LJU
In console
Initialized
localhost:6001/xyz
On browser
Hello
Welcome to LJU
Tutorial on Middleware
In console
request received onMon Jun 10 2024 15:22:44 GMT-0700 (Pacific Daylight Time)
P a g e 34 | 50
Chapter 4 Express JS
Example 1
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.
c. 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).
t1.js
var express = require("express");
var app = express();
app.use(express.static(__dirname,{index:'t1.html'}));
app.use(express.urlencoded());
app.post("/login",(req,res,next)=>{
res.set("content-type","text/html");
res.write("<center><h1>Welcome " + req.body.name + "</h1>");
res.write("<center><h2>Your email id is " + req.body.email + "</h2>");
next();
});
app.post("/login",(req,res)=>{
if(req.body.newsletter == "on"){
res.write("<h3>Thank you for your subscription</h3><a href='/'>Logout</a>");
}else{
P a g e 35 | 50
Chapter 4 Express JS
<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>
Output:
P a g e 36 | 50
Chapter 4 Express JS
Example 2
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"/>
password: <input type="text" name="pwd"/>
<input type="submit"/>
</form>
</body>
</html>
App.js
const express=require("express");
const app=express();
app.use(express.urlencoded({extended:false}));
app.use(express.static(__dirname));
app.post("/check",(req,res,next)=>{
if(req.body.uname=="admin")
{
next();
}
else {
res.send("<h1 style='color:red'>wrong credentials</h1>") }
});
app.post("/check",(req,res)=>
{
res.write(“<h1>welcome...”+ req.body.uname+ “</h1>”)
res.send();
}
P a g e 37 | 50
Chapter 4 Express JS
).listen(3001);
Cookie
How cookies work
When a user visits a cookie-enabled website for the first time, the browser will prompt
the user that the web page uses cookies and request the user to accept cookies to be
saved on their computer. Typically, when a makes a user request, the server responds by
sending back a cookie (among many other things).
This cookie is going to be stored in the user’s browser. When a user visits the website or
sends another request, that request will be sent back together with the cookies. The
cookie will have certain information about the user that the server can use to make
decisions on any other subsequent requests.
The major difference between sessions and cookies is that sessions live on the server-side (the
webserver), and cookies live on the client-side (the user browser). Sessions have sensitive
information such as usernames and passwords. This is why they are stored on the server.
Sessions can be used to identify and validate which user is making a request.
As we have explained, cookies are stored in the browser, and no sensitive information can be
stored in them. They are typically used to save a user’s preferences.
cookie-parser - cookie-parser looks at the headers in between the client and the server
transactions, reads these headers, parses out the cookies being sent, and saves them in a
browser. In other words, cookie-parser will help us create and manage cookies depending
on the request a user makes to the server.
P a g e 38 | 50
Chapter 4 Express JS
Example
app.js
var express = require('express');
var app = express();
var cp = require('cookie-parser');
app.use(cp());
res.clearCookie('fname');
});
app.listen(3000);
When the above route is executed from a browser, the client sends a get request to the server.
But in this case,
the server will respond with a cookie and save it in the browser.
To confirm that the cookie was saved, go to your browser’s Inspect element > select the
application tab > cookies > select your domain URL.
To check if your cookie is set or not, just go to your browser, fire up the console, and enter −
console.log(document.cookie);
P a g e 40 | 50
Chapter 4 Express JS
Example
Write an express js script to set cookies of submitted values of form. Perform following tasks.
Create a HTML file which contains a form with fields first name, last name, password
and a submit button.
Once form submitted, store all these entered values to the respective cookies on ‘/next’
page.
Then redirect user to “/admin” page and clear the cookie set for the last name. Display
remaining set cookie values on this page. (Using post method)
c1.html
<html>
<body>
<form method="post" action="/next">
First Name : <input type = "text" name="fname" ></input>
Last Name : <input type = "text" name="lname" ></input>
Password : <input type = "password" name="password" ></input>
<button name="Submit" value="Submit">Submit</button>
</form>
</body>
</html>
c1.js
var express = require("express");
var app = express();
var cp = require("cookie-parser");
app.use(cp());
app.use(express.static(__dirname,{index: 'c1.html'}));
app.use(express.urlencoded())
app.post("/next",(req,res,next)=>{
res.cookie("fname", req.body.fname);
res.cookie("password", req.body.password)
res.cookie("lname", req.body.lname);
res.redirect("/admin");
})
app.get("/admin",(req,res)=>{
res.clearCookie('lname');
res.write(" Welcome : " + req.cookies.fname);
P a g e 41 | 50
Chapter 4 Express JS
res.send()
});
app.listen(3000);
Example
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:
o Name (input field)
o Email (input field)
o Message (textarea field)
o 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.
feedback.js
P a g e 42 | 50
Chapter 4 Express JS
app.use(express.static(__dirname,{index:’feedback.html’}))
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(3000, () => {
console.log('Server is running on port 3000');
});
feedback.html
<!DOCTYPE html>
<html>
<head>
<title>User Feedback Form</title>
P a g e 43 | 50
Chapter 4 Express JS
</head>
<body>
<h1>User Feedback Form</h1>
<form action="/submit-feedback" method="POST">
<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>
P a g e 44 | 50
Chapter 4 Express JS
Session
HTTP is stateless; in order to associate a request to any other request, you need a way to store
user data between HTTP requests. Cookies and URL parameters are both suitable ways to
transport data between the client and the server. But they are both readable and on the client
side. Sessions solve exactly this problem. You assign the client an ID and it makes all further
requests using that ID. Information associated with the client is stored on the server linked to
this ID. Install the using the command:
To set up the session, you need to set a couple of Express-session options, as shown below.
resave
saveUninitialized
P a g e 45 | 50
Chapter 4 Express JS
cookie
{ maxAge: oneDay } - this sets the cookie expiry time. The browser will delete the cookie after
the set duration elapses. The cookie will not be attached to any of the requests in the future. In
this case, we’ve set the maxAge to a single day as computed by the following arithmetic.
Examples
Write express js script using session to display how many times a user visited a website. If user
is visiting a website for the first time then display “Welcome! Thank you for visiting our
website!” else display the count of user (How many times) for that particular session.
const express=require("express");
const app=express();
const sess=require("express-session");
app.use(sess(
{
resave:true,
saveUninitialized:true,
secret:"LJU123"
}
));
app.get("/",(req,res)=>
{
if(req.session.page_views)
{
req.session.page_views++;
res.send(`<h1 style="color:blue;"> You have visited page ${req.session.page_views} times
<h1>`);
}
else{
req.session.page_views=1;
res.send(`<h1 style="color:green;"> Welcome! Thank you for visiting our
website!<h1>`);
}
});
app.listen(8003,()=>{console.log("server running at 8003");});
P a g e 46 | 50
Chapter 4 Express JS
Example
write a script to meet following requirements:
Create index.html file page which contains form(username,password,login button).
and open it on localhost.
After clicking submit button, it should jump on “savesession” page. Store username
and password in session.
After saving session, redirect to “fetchsession” page and read value. Put a LOGOUT
link button here.
Jump on delete session page after clicking LOGOUT button.
Destroy the session on this page and redirect to index.html page.
session.js
var express = require("express");
var app = express();
var es = require("express-session");
app.use(es({
resave:false,
saveUninitialized:false,
secret:"lju1"
}));
app.use(express.static(__dirname));
app.get("/savesession",(req,res)=>{
req.session.uname = req.query.uname;
req.session.password = req.query.password;
res.redirect("fetchsession")
})
app.get("/fetchsession",(req,res)=>{
res.write("<h1>Welcome " + req.session.uname +"</h1>")
res.write("<a href='/deletesession'>Logout</a>")
res.send();
});
app.get("/deletesession",(req,res)=>{
req.session.destroy()
res.redirect('/')
});
app.listen(6177);
P a g e 47 | 50
Chapter 4 Express JS
index.html
<html>
<body>
<center>
<form method="get" action="/savesession">
<div><input type = "text" name="uname" placeholder="Username" ></input></div>
<div><input type = "password" name="pass" placeholder="Password"></input></div>
<input class="lj_in" type="submit" name="submit" value="Login">
</form>
</center>
</body>
</html>
Example
write a script to meet following requirements:
Create session.html file page which contains form(username,password,login button).
and open it on localhost.
After clicking submit button, it should jump on “save” page. Store username and
password in session.
After saving session, redirect to “fetchdata” page and read value. On this page check
authentication of user. User name and password must be “admin” and “admin@123”
respectively.
o If this condition is true then display welcome admin and display logout link on
this page(fetchdata).
By clicking on logout link user should jump to “destroy” page and destroy
the session there and display the message “Session destroyed”. And give
the link of “login” under that message. By clicking that link user will be
redirected to the home page.
o Else display “Please enter valid username and password” and login link on this
page(fetchdata).
session.html
<html>
<body>
<center>
<form method="get" action="/save">
<div><input type = "text" name="uname" placeholder="Username" ></input></div>
<div><input type = "password" name="pass" placeholder="Password"></input></div>
P a g e 48 | 50
Chapter 4 Express JS
Session.js
var express = require("express");
var app = express();
var es = require("express-session");
app.use(es({
resave:false,
saveUninitialized:false,
secret:"lju1"
}));
app.use(express.static(__dirname,{index:’session.html’}));
app.get("/save",(req,res)=>{
req.session.uname = req.query.uname;
req.session.password = req.query.pass;
res.redirect("fetchdata")
})
app.get("/fetchdata",(req,res)=>{
if(req.session.uname == "admin" && req.session.password=="admin@123"){
res.write("<h1 style='color:green;'>Welcome Admin</h1>")
res.write("<a href='/destroy'>Logout</a>")
}else{
res.write("<h1 style='color:red;'>Please enter valid username or password</h1><a
href='/'>Login</a>")
}
res.send();
});
app.get("/destroy",(req,res)=>{
req.session.destroy()
res.write("<h1>Session Destroyed</h1><a href='/'>Login</a>")
res.send();
});
app.listen(6177);
P a g e 49 | 50
Chapter 4 Express JS
Miscellaneous Task
If you want to set 404 status code on page not found error.
const express=require("express");
const app=express();
app.get("/",(req,res)=>
{
res.write("Home Page"); res.send();
})
app.get("/student",(req,res)=>
{
res.write("Student Page"); res.send();
})
app.get("*",(req,res)=>
{
res.status(404).end("page not found");
})
app.listen(8081,()=>{console.log("server started");})
P a g e 50 | 50