0% found this document useful (0 votes)
87 views21 pages

Lecture 11,12 Express

The document discusses Express, a web application framework for Node.js. It describes Express as a series of middleware function calls that facilitates rapid development of Node web apps. Express handles HTTP requests and responses, and makes it easier to organize app functionality into modular middleware. It helps abstract away Node complexities. Routing allows partitioning app behavior by route, and middleware functions have access to the request and response objects to modify them.

Uploaded by

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

Lecture 11,12 Express

The document discusses Express, a web application framework for Node.js. It describes Express as a series of middleware function calls that facilitates rapid development of Node web apps. Express handles HTTP requests and responses, and makes it easier to organize app functionality into modular middleware. It helps abstract away Node complexities. Routing allows partitioning app behavior by route, and middleware functions have access to the request and response objects to modify them.

Uploaded by

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

Lecture 11, 12

Instructor: Humaira Waqas

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 1


EXPRESS
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.
 It is Node.js web application framework
 It facilitates the rapid development of Node based web applications
 It acts as a middleware to respond to HTTP requests
 Facilitates the rendering of dynamic HTML views
 Easier to organize applications functionalities with the middleware.
 It helps to abstract away lot of Node.js complexities to simple code
 It lets you refactor one monolithic request handler function into many smaller request
handlers that handle only specific bits and pieces, which is more maintainable and
modular.

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 2


EXPRESS
• Express
• npx express-generator You can run the application generator with the npx
command (available in Node.js 8.2.0)
• or npm install -g express-generator For earlier Node versions, install the application
generator as a global npm package and then launch
• Express myapp creates an Express app named myapp
•cd myapp
• npm install install dependencies
•npm start start the server
• http://localhost:3000/ access the browser
• npm install nodemon
• npm i –d nodemon or npm i –g nodemon
WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 3
.
├── app.js
├── bin
EXPRESS │ └── www
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ └── stylesheets
│ └── style.css
├── routes
│ ├── index.js
│ └── users.js
└── views
├── error.pug
├── index.pug
└── layout.pug

7 directories, 9 files
WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 4
EXPRESS - MIDDLEWARE
Middleware
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.
Middleware functions can perform the following tasks:
• Execute any code.
• Make changes to the request and the response objects.
• Call the next middleware function in the stack.
• End the request-response cycle.
WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 5
EXPRESS - MIDDLEWARE
• When a request is received by Express, each middleware that matches the request is run in the
order it is initialized until there is a terminating action (like a response being sent).
• If an error occurs, all middleware that is meant to handle errors will be called in order until one of
them does not call the next() function call.

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 6


EXPRESS - MIDDLEWARE
Middleware functions are functions that have access to the request object (req),
the response object (res), and the next function in the applications request-
response cycle.
Request: it is the HTTP request that reaches the Express application when a client
makes HTTP request (PUT, GET, DELETE etc)
Response: it represents the HTTP response that an Express application sends when
it get an HTTP request
Next: next function in the middleware stack.
Request-response cycle: the cycle of operations that get executed starting with a
request hitting the Express application till the response leaves the application
Middleware stack: Stack of middleware functions that get executed for a
request-response cycle. WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 7
EXPRESS - MIDDLEWARE

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 8


EXPRESS - MIDDLEWARE
Define middleware function
function logger(req, res, next){
next() //calls the next function in the middleware stack
}
req is the HTTP request object.
res is the response object
next is the next function in request-response cycle.
Call Middleware
In express application, you call middleware using use function on application
object.
app.use(logger) WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 9
EXPRESS - ROUTING
Routing is the process of selecting a path for traffic in a network or between or across
multiple networks.
• Like middleware, it breaks the one monolithic request handler function into smaller
pieces.
• Unlike middleware, these request handlers are executed conditionally, depending on
what URL and HTTP method a client sends.
• For example, you might build a web page with a homepage and a guestbook.
• When the user sends an HTTP GET to the homepage URL, Express should send the homepage. But
when they visit the guestbook URL, it should send them the HTML for the guestbook, not for the
homepage!
• And if they post a comment in the guestbook (with an HTTP POST to a particular URL), this should
update the guestbook.
• Routing allows you to partition your application’s behavior by route.
WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 10
EXPRESS - ROUTER
Express router is a class (Express.Router) which helps us to create router handlers
Define routes
app.method(path, handler)
The method can be applied to any one of the HTTP verbs – get, set, put, delete.
An alternate method also exists, which executes independent of the request type.
Path is the route at which the request will run
Router handler
Router handler is a callback function that executes when a matching request type is found on
the relevant route.

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 11


EXPRESS - MIDDLEWARE
app.use(middleware) called every time a request is sent to the server
or used to mount the middleware function to a specified path
(the middleware function is executed when the base path
matches)
app.all() special routing methods which is used to load middleware functions at a path for all
HTTP request methods.
app.get()
app.post()
app.put()
app.delete()
app.set(‘title’, ‘Express Server’) gives a common place to read and write application wide settings. This code
will assign the server setting title to express server
app.get() get these values back using app.get(‘title’)
WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 12
EXPRESS - MIDDLEWARE
HTTP method for which the middleware function applies.
Path (route) for which the middleware function applies.

The middleware function.

Callback argument to the middleware function,


called "next" by convention.

HTTP response argument to the middleware


function, called "res" by convention.
HTTP request argument to the middleware
function, called "req" by convention. WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 13
EXPRESS – ROUTING
Static Routes
App.get(‘/’, requestProcessFunction)
App.get(‘/student’, requestProcessFunction)
Dynamic Routes
Express path with route parameters like:
 /:id , /:id?
 /student/:status/current/:id
 /student/:status/alumini/:batch?
The route parameters :status and :id will be parsed from the URI and made available via
req.params.status and req.params.id
Optional parameter is defined by ? as a postfix on a parameter e.g. :batch?
Express also allows regular expressions to be used as URI’s
 app.get('/things/:id([0-9]{5})', function(req, res){ } WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 14
EXPRESS – REQUEST OBJECT
Express request object represents the HTTP request and has properties for the
request
 query string
 Parameters
 Body
 HTTP headers
req.path it contains the path part of the request URL
req.query object containing a property for each query string parameter in the route
req.body contains key-value pairs of data submitted in the request bosy
req.get

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 15


EXPRESS – RESPONSE OBJECT
res.write build up the response body with content
res.status set the HTTP status code of the reply
res.end end the request by responding to it
res.send do a write and end

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 16


EXPRESS – ROUTING
express.static(root)
To use multiple static assets directories, call the express.static middleware
function
app.use("/", express.static(__dirname));
 __dirname is a global object that contains the name of the directory that the executing
script resides from. For example, if you are running node script.js from /home/user/env, then
__dirname will contain `/home/user/env.

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 17


EXPRESS - ROUTING
app.all('*', function(req, res, next) {
res.writeHead(404, { 'Content-Type': 'text/html' });
res.end('404 - Page Not Found');
});
Here * is a wild card and app.all means all methods.

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 18


EXPRESS - ROUTING
Template file doesn’t need to have the file extension suffix, so index.jade can just be referenced as
index. You also don’t need to specify the path to the view folder because you’ve already done this
in the main Express setup.
res.render is the Express function for compiling a view template to send as the HTML response that
the browser will receive.
The render method takes the name of the view template and a JavaScript data object in the
following construct:

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 19


EXPRESS - ROUTING
Template file doesn’t need to have the file extension suffix, so index.jade can just be referenced as
index. You also don’t need to specify the path to the view folder because you’ve already done this
in the main Express setup.
res.render is the Express function for compiling a view template to send as the HTML response that
the browser will receive.
The render method takes the name of the view template and a JavaScript data object in the
following construct:

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 20


DISCUSSION

WEB TECHNOLOGIES AND PROGRAMMING (BY: HUMAIRA WAQAS) 21

You might also like