Server Side development with Express(E):
Topic: Introduction to the Express Framework:
Q1) What is Express Framework? Write any 3 features of it.
a) [Link] is a web framework for [Link]. It is a fast, robust and
asynchronous in nature.
b) Express is a minimal and flexible [Link] web application
framework that provides a robust set of features to develop web and
mobile application
features of Express framework:
o It can be used to design single-page, multi-page and hybrid web
applications.
o It allows to setup middlewares 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.
Topic: Installing and testing Express:
Q2) Write the commands which help us to install express js.
In command prompt type following 4 commands.
a) npm install --save express
b) npm install body-parser --save
c) npm install cookie-parser --save
d) npm install multer --save
The above command saves the installation locally in
the node_modules directory and creates a directory express inside
node_modules.
You should install the following important modules along with express
−
• body-parser − This is a [Link] middleware for handling
JSON, Raw, Text and URL encoded form data.
• cookie-parser − Parse Cookie header and populate
[Link] with an object keyed by the cookie names.
• multer − This is a [Link] middleware for handling
multipart/form-data.
Topic: Creating a node js express App:
Q3) Write an express application to display Hello world on server
which listens on port 8081.
Following is a very basic Express app which starts a server and listens
on port 8081 for connection.
This app responds with Hello World! for requests to the homepage.
For every other path, it will respond with a 404 Not Found.
var express = require('express');
var app = express();
[Link]('/', function (req, res) {
[Link]('Hello World');
})
var server = [Link](8081, function () {
})
Save the above code in a file named [Link] and run it with the
following command.
$ node [Link]
Import express with require keyword and create an app by calling
the express() function provided by the express framework. Call
the listen() function, It requires port and callback function as an
argument. It starts listening to the connection on the specified path,
the default host is localhost and on mentioned port.
With [Link]() we are configuring our first route, it requires two
arguments first one is the path and, the second one is a function that
will be executed when anyone requests this path with GET method.
The express provides the request and response object as a parameter
to all such types of functions.
Finally, we are returning the response to the user. The send() method
takes a string, object, array, or buffer as an argument and is used to send
the data object back to the client as an HTTP response, also there are
lots of types of response in express like [Link]() which is used to send
JSON object, [Link]() which is used to send a file, etc.
Topic: structuring an Express App:
[Link]
express-js/
Create Node Project:
Step 1: As the express application is built upon NodeJS so first of
all, we have to initialize a node project, write the command below in
your terminal.
npm init
Step 2: Install Packages
npm install express
Step 3: Create an [Link] file. In this file, we write the entire code of
the server.
touch [Link]
Project Structure: After all of this, our project structure will look
like this.
Structure of [Link] file: Imports are the first thing that should be
written inside this file and then some kind of initialization can be
done here.
The detailed info is available on the provided link which is not
required exam point of view.
Topic: creating templates:
Express templates:
[Link]
Pug is a templating engine for Express. Templating engines are used to
remove the cluttering of our server code with HTML,
concatenating strings wildly to existing HTML templates.
Pug is a very powerful templating engine which has a variety of
features including filters, includes, inheritance, interpolation, etc.
To use Pug with Express, we need to install it,
npm install --save pug
Now that Pug is installed, set it as the templating engine for your app.
You don't need to 'require' it.
Pug provides a very intuitive way to create components for a web page.
For example, if you see a news website, the header with logo and
categories is always fixed. Instead of copying that to every view we
create, we can use the include feature. Following example shows how
we can use this feature –
Q4) Write an express app to create 3 template views header ,
content and footer pug files and call through express app.
Create 3 views with the following code −
[Link] file
[Link].
I'm the header for this website.
[Link] file
html
head
title Simple template
body
include ./[Link]
h3 I'm the main content
include ./[Link]
[Link]
[Link].
I'm the footer for this website.
Create a route for this as follows using express node js main file −
var express = require('express');
var app = express();
[Link]('/components', function(req, res){
[Link]('content');
});
[Link](3000);
Go to localhost:3000/components, you will receive the following
output –
ExpressJS - Templating ([Link])
Topic: Using express middleware functions:
[Link]
Express is a routing and middleware web framework that has minimal
functionality of its own: An Express application is essentially a series
of middleware function calls.
Middleware functions are functions that have access to the request
object (req), the response object (res), and the next middleware
function in the application’s request-response cycle. The next
middleware function is commonly denoted by a variable named next.
Middleware functions can perform the following tasks:
• Execute any code.
• Make changes to the request and the response objects.
• End the request-response cycle.
• Call the next middleware function in the stack.
If the current middleware function does not end the request-response
cycle, it must call next() to pass control to the next middleware
function. Otherwise, the request will be left hanging.
[Link]
Middleware functions are functions that have access to the request
object (req), the response object (res), and the next middleware
function in the application’s request-response cycle. These functions
are used to modify req and res objects for tasks like parsing request
bodies, adding response headers, etc.
Here is a simple example of a middleware function in action –
Order of Middleware Calls
One of the most important things about middleware in Express is the
order in which they are written/included in your file; the order in which
they are executed, given that the route matches also needs to be
considered.
For example, in the following code snippet, the first function executes
first, then the route handler and then the end function. This example
summarizes how to use middleware before and after route handler; also
how a route handler can be used as a middleware itself.
Q) WAP in express to display start and end messages in console
and hello world on web browser using middleware functions.
var express = require('express');
var app = express();
//First middleware before response is sent
[Link](function(req, res, next){
[Link]("Start");
next();
});
//Route handler
[Link]('/', function(req, res, next){
[Link]("Middle");
next();
});
[Link]('/', function(req, res){
[Link]('End');
});
[Link](3000);
When we visit '/' after running this code on web browser , we receive
the response as Middle and on our console −
Start
End
Topic: Creating the List Page
Q) Write an express app to display list of users by exporting user
defined module.
const users = [ { name: "mahesh" }, { name:
"suresh" }, { name: "ramesh"} ];
[Link] = users;
var express = require('express');
var app = express();
let users = require(“/Users”);
// This responds a GET request for the /list_user page.
[Link]('/users', function (req, res) {
[Link](“Users” <a href=”#newuser”>Create new user</a>”);
[Link](users);
})
var server = [Link](3000, function () {
})
Save the above code in a file named [Link] and run it with the
following command.
$ node [Link]
Screen showing again [Link]
extends layout
block content
h1= title
p Welcome to Royal College Library
h1 Dynamic content
if error
p Error getting dynamic content.
else
p The library has the following record counts:
ul
li # strong Books: 5
li # strong Copies: 6
li # strong Copies available: 5
Topic: creating the List Page, Creating the Details Page. Creating the
Edit Page. Creating the Add Page. Deleting Data.
Write an express application to display the resource and delete the
existing resource.
Q1) WAP USING EXPRESS TO DISPLAY JSON ARRAY OF USER LIST DATA.
[Link] file
const users = [ { name:
"mahesh" }, { name: "suresh" }, { name:
"ramesh"} ];
[Link] = users;
JS FILE
var express = require('express');
var app = express();
let users = require(“/users”);
[Link]('/listusers', function (req, res) {
[Link](users');
});
_____________________________Or
JS FILE
var express = require('express');
var app = express();
[Link]('/listusers', function (req, res) {
[Link]("book_list", { title: "Book List"
});
});
book_list.pug file (template file)
extends layout
block content
h1= title
ul
li # strong Books: 15
li # strong Copies: 6
li # strong Copies available: 5
Q2) WAP USING EXPRESS TO DISPLAY THE CONTENTS OF HTML FILE .
[Link] file (ANY HTML FILE)
<html><body><h1>Users Details </h1><a
href=”[Link]”>SY</a></body></html>
JS FILE
var express = require('express');
var app = express();
[Link]('/userdetails', function (req, res) {
[Link]('[Link]');
});
Q3) WAP USING EXPRESS TO DISPLAY ADD NEW USER HTML
FILE & DISPLAY THE FIRST NAME AND LAST NAME ENETERED
BY USER.
[Link]
<html><head> <title>Add new user</title></head>
<body>
<form action="/submit-student-data"
method="post">
First Name: <input name="firstName"
type="text" /> <br />
Last Name: <input name="lastName"
type="text" /> <br />
<input type="submit" />
</form>
</body>
</html>
JS FILE:
var express = require('express');
var app = express();
var bodyParser = require("body-parser");
[Link]([Link]({ extended: false }));
[Link]('/Adduser', function (req, res) {
[Link]('[Link]');
});
[Link]('/submit-student-data', function (req, res)
{
var name = [Link] + ' ' +
[Link];
[Link](name + ' Submitted Successfully!');
});
var server = [Link](5000, function () {
[Link]('Node server is running..');
});
Body Parser
To handle HTTP POST request in [Link] version 4 and above,
you need to install middleware module called body-parser.
This body-parser module parses the JSON, buffer, string and url
encoded data submitted using HTTP POST request.
Install body-parser using NPM as shown below.
npm install body-parser --save
Now, import body-parser and get the POST request data as shown
below.
Now, run the above example using node [Link] command, point
your browser to [Link] and see the following result.
[Link]
Q4) Write an express code to call put and delete
requests.
POST /movies Creates a new movie with the details provided. Response
contains the URI for this newly created resource.
PUT /movies/1234 Modifies movie id 1234(creates one if it doesn't already exist).
Response contains the URI for this newly created resource.
DELETE /movies/1234 Movie id 1234 should be deleted, if it exists. Response should
contain the status of the request.
JS FILE:
var express = require('express');
var app = express();
[Link]('/movies/1234', function (req, res) {
[Link]('PUT Request to update 1234 movie
details');
});
[Link]('/movies/5678', function (req, res) {
[Link]('DELETE Request');
});
var server = [Link](5000, function () {
[Link]('server is running..');
});
Optional information: above content in one file
var express = require('express');
var app = express();
// This responds with "Hello World" on the homepage
[Link]('/', function (req, res) {
[Link]("Got a GET request for the homepage");
[Link]('Hello GET');
})
// This responds a POST request for the homepage
[Link]('/', function (req, res) {
[Link]("Got a POST request for the homepage");
[Link]('Hello POST');
})
// This responds a DELETE request for the /del_user page.
[Link]('/del_user', function (req, res) {
[Link]("Got a DELETE request for /del_user");
[Link]('Hello DELETE');
})
[Link](8081, function () {
[Link]("Server running”)
})
Save the above code in a file named [Link] and run it with the
following command.
$ node [Link]
Topic: Rest API basics, Testing and Refactoring API
[Link]
REST API is a software architecture to create web frameworks
. REST(Representational Transfer State).
We should follow REST architecture style if wants to design web page.
HTTP 1.1 was designed keeping REST principles in mind. RESTful
URIs and methods provide us with almost all information we need to
process a request. The table given below summarizes how the various
verbs should be used and how URIs should be named. We will be
creating a movies API towards the end; let us now discuss how it will
be structured.
Method URI Details Function
GET /movies Safe, Gets the list of all movies and their deta
cachable
GET /movies/1234 Safe, Gets the details of Movie id 1234
cachable
POST /movies N/A Creates a new movie with the details
provided. Response contains the URI fo
this newly created resource.
PUT /movies/1234 Idempotent Modifies movie id 1234(creates one if it
doesn't already exist). Response contain
the URI for this newly created resource.
DELETE /movies/1234 Idempotent Movie id 1234 should be deleted, if it
exists. Response should contain the statu
of the request.
DELETE /movies Invalid Should be
or PUT invalid. DELETE and PUT should
specify which resource they are working
on.
Let us now create this API in Express. We will be using JSON as our
transport data format as it is easy to work with in JavaScript and has
other benefits. Replace your [Link] file with the [Link] file as in
the following program.
[Link]
var express = require('express');
var app = express();
//Require the Router we defined in [Link]
var movies = require('./[Link]');
//Use the Router on the sub route /movies
[Link]('/movies', movies);
[Link](3000);
Start by setting up the [Link] file. We are not using a database to
store the movies but are storing them in memory; so every time the
server restarts, the movies added by us will vanish. Once you import
Express then, create a Router and export it using [Link] −
var express = require('express');
var router = [Link]();
var movies = [
{id: 101, name: "Fight Club", year: 1999, rating: 8.1},
{id: 102, name: "Inception", year: 2010, rating: 8.7},
{id: 103, name: "The Dark Knight", year: 2008, rating: 9},
{id: 104, name: "12 Angry Men", year: 1957, rating: 8.9}
];
//Routes will go here
[Link] = router;
GET routes
Let us define the GET route for getting all the movies −
[Link]('/', function(req, res){
[Link](movies);
});
run your app by typing in browser localhost:3000/movies
The following response will be displayed −
[{"id":101,"name":"Fight Club","year":1999,"rating":8.1},
{"id":102,"name":"Inception","year":2010,"rating":8.7},
{"id":103,"name":"The Dark Knight","year":2008,"rating":9},
{"id":104,"name":"12 Angry Men","year":1957,"rating":8.9}]
END OF EXPRESS TOPIC