0% found this document useful (0 votes)
26 views28 pages

Chapter Four

The document provides an overview of the Express framework, a Node.js web application framework used for building web and mobile applications. It covers installation, usage, routing, middleware, serving static files, and integrating with EJS for templating, as well as the Nodemailer module for sending emails. Key concepts such as application objects, routing structure, and middleware functions are also discussed, along with examples for practical implementation.

Uploaded by

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

Chapter Four

The document provides an overview of the Express framework, a Node.js web application framework used for building web and mobile applications. It covers installation, usage, routing, middleware, serving static files, and integrating with EJS for templating, as well as the Nodemailer module for sending emails. Key concepts such as application objects, routing structure, and middleware functions are also discussed, along with examples for practical implementation.

Uploaded by

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

JUST UNIVERSITY

Ch04
Framework Express

Eng. Abdirizak Ibrahim Abdiwahid (Eng.Qeys)

1
Express Framework
• Express is a node js web application framework that
provides broad features for building web and mobile
applications. It is used to build a single page,
multipage, and hybrid web application.

• Express. js is a framework based on Node. js for


which is used for building web-application using
approaches and principles of Node

• The Express is framework makes it very easy to


develop an application which can be used to handle
multiple types of request .
Express used for
• Express provides methods to specify what

function is called for a particular HTTP verb ( GET

, POST , SET , etc.) and URL pattern ("Route"),

and methods to specify what template ("view")

engine is used, where template files are located,

and what template to use to render a response.


Installing Express
• Firstly, install the Express framework globally
using NPM so that it can be used to create a web
application using node terminal.
npm install express –save
npm install express
• The above command saves the installation
locally in the node_modules directory and
creates a directory express inside node_modules.
Usage
• Express module is factory for application
var app = expresss( );
• Application have many methods for
configuring
• Are also function that can be given to
standard node http and https modules
• Invoke app.listen() method after
configuring or give to http or https
modules
• App.listen (3000, function (req, res){
• Console.log(express ready for port
Objects of Express
• There are four main objects of Express :

Application (app)

Request (req)

Respond (res)

Router (express.router)
Routing
• Routing refers to determining how an
application responds to a client request to a
particular endpoint, which is a URI (or path) and a
specific HTTP request method (GET, POST, and so
on).
• Each route can have one or more handler
functions, which are executed when the route is
matched.
• Route definition takes the following structure:
app.METHOD(PATH, HANDLER)
• app is an instance of express.
• METHOD is an HTTP request method, in
lowercase.
• PATH is a path on the server.
Example
app.get('/', (req, res) => {
res.send('Hello World!')
})

a route handler is code that is looking for a


request to a specific incoming URL such as /login
and often a specific HTTP verb such as POST and
has specific code for handling that precise URL
and verb.

Respond to POST request on the root route (/),


Objects of Express
• app. get( ) is a function that tells the server what to
do when a get request at the given route is called. It
has a callback function (req, res) that listen to the
incoming request req object and respond accordingly
using res response object.

• app. use ( ) method mounts or puts the specified


middleware functions at the specified path.

This middleware function will be executed only when the


base of the requested path matches the defined path
Continue…
• app.set( ) function is used to assigns
the setting name to value. You may store
any value that you want, but certain
names can be used to configure the
behavior of the server. app.set(name, value)

• App.redirector ( )
Middleware
• 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.
elements of a
middleware
• The following figure shows the elements
of a middleware function call:
Example Using Next () Middle
Ware
• Using next(): If you have any middleware
function and below the next() you have some
lines or function that you want to execute, then
by using next() you can actually execute the lines
or function because it runs the code
below next() after all middleware function
finished.
Example of Next()
Middleware
• const express = require('express')
• const app = express();

app.use((req, res, next)=>{
• console.log('first middle ware')
• next();
• })

app.use((req, res, next)=>{


• console.log('secnode middle ware')
• next();
• })

app.use((req, res, next)=>{
• console.log('third middle ware')
• })

app.listen(5000)
serve static
files
• To serve static files such as images, CSS files, and

JavaScript files, use the express.static built-in

middleware function in Express.

• The function signature is:

• express.static(root, [options])

• app.use(express.static('public'))
Serving static files
• Express provides a built-in middleware express.static to serve static

files, such as images, CSS, JavaScript, etc.

• You simply need to pass the name of the directory where you keep

your static assets, to the express.static middleware to start serving

the files directly.

• For example, if you keep your images, CSS, and JavaScript files in a

directory named public, you can do this − app.use(express.static

('public'));
NPM
• NPM : it is an online repository for the publishing
of open-source Node. js projects

• It helps with installing various packages and


resolving their various dependencies. It greatly
helps with your Node development.

• NPM helps you install the various modules you


need for your web development and not just given
you a whole bunch of features you might never
need
Most important Packages
• Nodemone : is a tool that helps
develop Node. js based applications by
automatically restarting the node
application when file changes in the
directory are detected.

• Npm install –g nodemon

• Npm init for install package json


Package.json file

• A Package.json (JavaScript Object Notation) file is

contains every information about any Express project.

The number of modules installed, the name of the

project, the version, and other meta information. To

add Express as a module in our project, first we need

to create a project directory and then create a

package.json file.
Example Express
• const express = require('express')
• const app = express();

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


• res.send('<h1>school management
system<h2>')
• })

app.listen(3000)
Routing Html Page
• const express = require('express')
• const app = express();

app.get('/' , (req , res)=>{
• res.sendFile('./views/index.html',
{root:__dirname})
• })

app.get('/about' ,(req , res)=>{
• res.sendFile('./views/about.html',
{root:__dirname})
• })
app.listen(3000)
Routing Html Page
• const express = require('express')
• const app = express();

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


• res.sendFile('./views/index.html',{root:__dirname})
• })

app.get( '/about',(req , res)=>{
• res.sendFile('./views/about.html',{root:__dirname})
• })

app.use( (req , res)=>{
• res.sendFile('./views/404.html',{root:__dirname})
• })
• app.listen(3000)
What is EJS Templet

• EJS (Embedded
JavaScript Templating) is one of the
most popular template engines for
JavaScript. As the name suggests, it lets
us embed JavaScript code in a template
language that is then used to generate
HTML.

npm install -S express ejs


View engines
• View engines allow us to render web pages
using template files. These templates are filled
with actual data and served to the client. There are
multiple view engines, the most popular of which is
Embedded Javascript (EJS).
app.set('view engine', 'ejs');

• The res.render() function is used to render a view


and sends the rendered HTML string to the client.
Examples Ejs and View

Engine
const express = require('express')
• const app = express()

// register view engine


• app.set('view engine', 'ejs')
• app.get('/',(req , res)=>{
• res.render('index')
• });

app.get('/about',(req , res)=>{
• res.render('about')
• });

app.get('/register',(req ,res)=>{
• res.render('register')
• })

app.use((req ,res)=>{
• res.status(404).render('404')
• })
Nodemailer Module
• Nodemailer is a Node. js module that
allows you to send emails from your
server with ease. Whether you want to
communicate with your users or just
notify yourself when something has gone
wrong, one of the options for doing so is
through mail.
Example of
NodeMailer Module
• npm install nodemailer
• var transporter = nodemailer.createTransport({
service: 'gmail',
auth: {
user: '[email protected]',
pass: 'yourpassword'
}
});

var mailOptions = {
from: '[email protected]',
to: '[email protected]',
subject: 'Sending Email using Node.js',
text: 'That was easy!'
};

transporter.sendMail(mailOptions, function(error, info){


if (error) {
console.log(error);
} else {
console.log('Email sent: ' + info.response);
}
})
END
28

You might also like