Unit-4 Express Js
Unit-4 Express Js
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.
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
app.listen(6000);
Response methods
The methods on the response object (res) in the following table can send a response to the client.
Method Description
Example
index.js
const expr = require("express");
{ res.set ("content-type","text/plain");
res.send ("<h1>Hello</h1>");
});
{ res.set ("content-type","text/html");
res.write ("Hello");
});
app.listen (5000,()=>
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.
Where:
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.
You can replace '123' in the URL with anything else and the change will reflect in the response.
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.
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:
if you pass in an object or an array, it sets the application/json Content-Type header, and
parses that parameter into JSON.
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()
every network call with a Request object instance and a Response object instance.
Example:
You can send JSON to the client by using Response.json() , a useful method.
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().
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")
})
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")
for(i of student.A1){
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)
app.use(express.static('public'));
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”
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
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");
});
On browser: localhost:5000/
If you want to open html file with other name like second.html then write below code.
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"/>
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
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>
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.
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)=>
{
});
app.get("/hello",(req,res)=>
{
res.send();
}).listen(5000);
Program:
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
app.listen(5001);
/public/home.html
<label for="email">Email:</label>
<input type="email" name="email" required><br><br>
<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.
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.
Adding cookies
To use a new cookie, first define a new route in your express.js app like:-
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.
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});
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>
<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;
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.
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.
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
Cookies expire after the The session ends when the user closes
Expiry user specified lifetime. the browser or logs out of the
program.
Installation
Installation is done using the npm install command:
npm install 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)=>
{
<html>
<head>
<title> Website</title>
</head>
<body>
<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)=>
{
})
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");
});