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

Node - Js - Express Framework

The document provides an overview of the Express framework: - Express is a web application framework for Node.js that simplifies building web servers and APIs and adds features like routing and middleware. - It allows setting up middleware to handle HTTP requests and defines a routing table to perform actions based on the request method and URL. - Express makes it easier to organize apps, render dynamic HTML views, and define extensibility standards for Node.js HTTP servers.

Uploaded by

B. POORNIMA
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
148 views

Node - Js - Express Framework

The document provides an overview of the Express framework: - Express is a web application framework for Node.js that simplifies building web servers and APIs and adds features like routing and middleware. - It allows setting up middleware to handle HTTP requests and defines a routing table to perform actions based on the request method and URL. - Express makes it easier to organize apps, render dynamic HTML views, and define extensibility standards for Node.js HTTP servers.

Uploaded by

B. POORNIMA
Copyright
© © All Rights Reserved
Available Formats
Download as PPT, PDF, TXT or read online on Scribd
You are on page 1/ 36

Node.

js - Express
Framework
Introduction
 Express is a relatively small framework that sits on top of
Node.js’s 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’s HTTP objects; it facilitates
the rendering of dynamic HTML views; it defines an easily
implemented extensibility standard.
  It is a fast, robust and asynchronous in nature.
 It can be used to design single-page, multi-page and hybrid
web applications.
 It allows to setup middlewares to respond to HTTP
Requests.
 It defines a routing table which is used to perform different
actions based on HTTP method and URL.
 It allows to dynamically render HTML Pages based on
passing arguments to templates.
Installing Express
 The above commands 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 node.js middleware for
handling JSON, Raw, Text and URL encoded form
data.
 cookie-parser − Parse Cookie header and
populate req.cookies with an object keyed by
the cookie names. Note: No need to
install npm
 multer − This is a node.js middleware for
packages, already
available in
handling multipart/form-data. node_modules
Writing middleware for use in
Express apps
 Middleware functions are functions that have access to
the request object (req), the response object (res), and
the next() function in the application’s request-response
cycle. The next() function is a function in the Express
router which, when invoked, executes the middleware
succeeding the current middleware.
 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 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
The following figure shows the
elements of a middleware
function call:
Example with middleware
 Here is an example of a simple “Hello World”
Express application.

 Here is a simple example of a middleware function called


“myLogger”. This function just prints “LOGGED” when a
request to the app passes through it. The middleware
function is assigned to a variable named myLogger.
•Notice the call above
to next(). Calling this
function invokes the next
middleware function in
the app.
•To load the middleware
function, call app.use().
 The order of middleware loading is important:
middleware functions that are loaded first are
also executed first.
 If myLogger is loaded after the route to the root
path, the request never reaches it and the app
doesn’t print “LOGGED”, because the route
handler of the root path terminates the request-
response cycle.
 The middleware function myLogger simply
prints a message, then passes on the request to
the next middleware function in the stack by
calling the next() function.
 Next, we’ll create a middleware function called
“requestTime” and add it as a property
called requestTime to the request object.
 When you make a request to the root of the app, the app now
displays the timestamp of your request in the browser.

 Because you have access to the request object, the response


object, the next middleware function in the stack, and the whole
Node.js API, the possibilities with middleware functions are endless.
In the above middleware
example a new function is used
to invoke with every request
via app.use().
Middleware is a function, just like
route handlers
You can add more middlewares
above or below using the same
API.
Express.js GET Method Example 1

index.html

get_ex1.js

Open the page index.html and


fill the entries:
Fetch data in paragraph
format
get_ex2.js
Express.js POST Method
index.html

post_ex1.js
Data Validation
 Express itself doesn't provide any specific
support for form handling operations, but it
can use middleware to
process POST and GET parameters from the
form, and to validate their values.
 import the express-validator module after
the other modules.
 checkBody(parameter, message): Specifies a body
(POST) parameter to validate along with a message to
be displayed if it fails the tests. The validation criteria
are daisy chained to the checkBody() method. For
example, the first check below will test that the
"name" parameter is alphanumeric and set an error
message "Invalid name" if it is not. The second test
checks that the age parameter has an integer value.
validation_ex.js
Express.js Routing
 It is used to determine the specific behavior of an application.
It specifies how an application responds to a client request to a
particular route, URI or path and a specific HTTP request
method (GET, POST, etc.). It can handle different types of HTTP
requests.
◦ http://localhost:3000/Books
◦ http://localhost:3000/Students
 In the above example, If a GET request is made for the first
URL, then the response should ideally be a list of books. If the
GET request is made for the second URL, then the response
should ideally be a list of Students.
 So based on the URL which is accessed, a different
functionality on the web server will be invoked and accordingly
the response will be sent to the client. This is the concept of
routing.
 Each route can have one or more handler functions, which are
executed when the route is matched.
Configure Routes:
index.html
route_ex.js
Access MongoDB in
Node.js
Introduction to MongoDB
MongoDB is a No SQL database. It is
an open-source, cross-platform,
document-oriented database written in
C++.
Mongo DB is developed and supported
by a company named 10gen.
Main purpose to build MongoDB:
◦ Scalability
◦ Performance
◦ High Availability
◦ Scaling from single server deployments to large,
complex multi-site architectures.
Installation
 Node.js has the ability to work with both
MySQL and MongoDB as databases. In order to
use either of these databases, you need to
download and use the required modules using
the Node package manager.
 We first have to install MongoDB on Ubuntu
System by the following command
sudo apt-get install -y mongodb
 To start mongo db shell type

mongo
 Next we have to install MongoDB driver for
node.js through npm, if we want to use it as
our database.
MongoDB Shell
MongoDB have a JavaScript shell that
allows interaction with MongoDB
instance from the command line.
To start the shell, open command
prompt, run it as a administrator then
run the mongo executable:

The shell is a full-featured JavaScript


interpreter. It is capable of running
Arbitrary JavaScript program.
Shell command examples
Here database name is
mydb and collection
name is employee
Architecture
Mongodb connection

 The prototype has a single property – db which stores the


database connection; it's initialised to null in the constructor.
 The connect() method returns the database reference if the
specified database is already exists, otherwise it creates a
new database.
 The MongoDB driver is asynchronous (the function returns
without waiting for the requested operation to complete)
 The basic interaction model from the application should be:
◦ Connect to the database
◦ Perform all of the required database actions for the current
request
◦ Disconnect from the database
Create database
 There is no create database command in
MongoDB. Actually, MongoDB do not provide
any command to create database.
 Don't need to mention what you want to
create, it will be automatically created at the
time you save the value into the defined
collection.
 If there is no existing database, the following
command is used to create a new database.

 To check the database list, use the


command
Mongodb Objectid field
 If _id field value is not
provided mongodb creates a
hexadecimal field for _id field that is
used as a primary key.
Every document in a mongodb collection
requires an _id field. It is an auto
generated 12 bytes field consisting of 4
bytes for seconds from UNIX
timestamp, 3 bytes of machine
identifier, 2 bytes of process id and 3
bytes for a counter.
MongoDB Collections
 In MongoDB, db.createCollection(name, options) is
used to create collection. But usually you no need to
create collection. MongoDB creates collection
automatically when you insert some documents. 

 To check the created collection 


 To drop collection
Node.js script to Insert and Display
monogDB documents
Node.js script to Insert and
Count monogDB documents

 In the above example, db.collection() method creates or


gets the reference of the specified collection. Collection is
similar to table in relational database. We created a
collection called employee in the above example and
insert three documents (rows) in it. After that, we display
the count of total documents stored in the collection.
Node.js script to
Update/Delete monogDB
documents
Node.js script to Search
monogDB documents
Building a Simple CRUD web
Application with Express and
MongoDB
index.html
Display using Embedded
js Create
‘disp.ejs’ in
‘views ‘ folder

disp.ejs
Display in JSON format
Search module
search.html

Search and display the result in JSON format

You might also like