Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
9 views

PHP Programming

This document provides an overview of the Express web application framework for Node.js, including: 1) Express allows building web and mobile apps and handles multiple request types. It provides middleware, routing, and view rendering features. 2) Core features include middleware, routing tables to handle requests by HTTP method and URL, and rendering HTML templates. 3) Express is commonly used to specify routes and handlers for different HTTP verbs and URLs, set template engines, and render responses.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

PHP Programming

This document provides an overview of the Express web application framework for Node.js, including: 1) Express allows building web and mobile apps and handles multiple request types. It provides middleware, routing, and view rendering features. 2) Core features include middleware, routing tables to handle requests by HTTP method and URL, and rendering HTML templates. 3) Express is commonly used to specify routes and handlers for different HTTP verbs and URLs, set template engines, and render responses.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

JUST UNIVERSITY

Ch04
Express Framework

Eng. Abdirahman A. Mohamed (Baabale)

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 .
Continue..
• Express is a minimal and flexible Node.js web application
framework that provides a robust set of features to develop
web and mobile applications. It facilitates the rapid
development of Node-based Web applications.
Following are some of the core features of Express
framework
• Allows to set up middlewares to respond to HTTP
Requests.
• Defines a routing table which is used to perform different
actions based on HTTP Method and URL.
• Allows to dynamically render HTML Pages based on
passing arguments to templates.
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 3000’);
• });
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.
• HANDLER is the function executed when the route is
matched.
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

• Npm install express installing express


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

npm install 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')
• })
Basic Routing
• We have seen a basic application which serves
HTTP request for the homepage. 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.

• We will extend our Hello World program to handle


more types of HTTP requests.
Example Basic Routing
• var express = require('express');
• var app = express();

// This responds with "Hello World" on the homepage
• app.get('/', function (req, res) {
• console.log("Got a GET request for the homepage");
• res.send('Hello GET');
• })
// This responds a POST request for the homepage
• app.post('/', function (req, res) {
• console.log("Got a POST request for the homepage");
• res.send('Hello POST');
• })

// This responds a DELETE request for the /del_user page.


• app.delete('/del_user', function (req, res) {
• console.log("Got a DELETE request for /del_user");
• res.send('Hello DELETE');
• })
Examples
• var express = require('express');
• var app = express();

app.get('/', function (req, res) {
• res.send('Hello World');
• })
var server = app.listen(8081, function () {
• var host = server.address().address
• var port = server.address().port

• console.log("Example app listening at
http://%s:%s", host, port)
• })
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: 'youremail@gmail.com',
pass: 'yourpassword'
}
});

var mailOptions = {
from: 'youremail@gmail.com',
to: 'myfriend@yahoo.com',
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);
}
})

// This responds a GET request for the /list_user page.
• app.get('/list_user', function (req, res) {
• console.log("Got a GET request for /list_user");
• res.send('Page Listing');
• })

// This responds a GET request for abcd, abxcd, ab123cd, and so
on
• app.get('/ab*cd', function(req, res) {
• console.log("Got a GET request for /ab*cd");
• res.send('Page Pattern Match');
• })
var server = app.listen(8081, function () {
• var host = server.address().address
• var port = server.address().port

• console.log("Example app listening at http://%s:%s", host,
port)
END
33

You might also like