0% found this document useful (0 votes)
28 views22 pages

Express

The document provides an overview of routing and middleware in Express.js, a popular Node.js framework for building web applications and APIs. It explains how to define routes using HTTP methods, the importance of callback functions, and the various types of middleware available, including application-level, built-in, and third-party middleware. Additionally, it includes examples of middleware functions and their configurations, emphasizing the need to call 'next()' to pass control in the request-response cycle.
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)
28 views22 pages

Express

The document provides an overview of routing and middleware in Express.js, a popular Node.js framework for building web applications and APIs. It explains how to define routes using HTTP methods, the importance of callback functions, and the various types of middleware available, including application-level, built-in, and third-party middleware. Additionally, it includes examples of middleware functions and their configurations, emphasizing the need to call 'next()' to pass control in the request-response cycle.
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

Express

By Komal Singh
Routing

• Routing refers to how an application’s endpoints (URIs) respond to


client requests. For an introduction to routing, see Basic routing.
• You define routing using methods of the Express app object that
correspond to HTTP methods; for example, app.get() to handle GET
requests and app.post to handle POST requests.
• In fact, the routing methods can have more than one callback
function as arguments. With multiple callback functions, it is
important to provide next as an argument to the callback function
and then call next() within the body of the function to hand off
control to the next callback.
The following code is an example of a very basic
route.

• const express = require('express')


• const app = express()

• // respond with "hello world" when a GET request is made to the


homepage
• app.get('/', (req, res) => {
• res.send('hello world')
• })
Route methods

• A route method is derived from one of the HTTP methods, and is attached to an instance
of the express class.
• The following code is an example of routes that are defined for the GET and the POST
methods to the root of the app.
• // GET method route
• app.get('/', (req, res) => {
• res.send('GET request to the homepage')
• })
• // POST method route
• app.post('/', (req, res) => {
• res.send('POST request to the homepage')
• })
Response methods

• The methods on the response object (res) in the following table can
send a response to the client, and terminate the request-response
cycle.
• If none of these methods are called from a route handler, the client
request will be left hanging.
Method Description
res.download() Prompt a file to be downloaded.
res.end() End the response process.
res.json() Send a JSON response.
res.jsonp() Send a JSON response with JSONP support.

res.redirect() Redirect a request.


res.render() Render a view template.
res.send() Send a response of various types.
res.sendFile() Send a file as an octet stream.
res.sendStatus() Set the response status code and send its
string representation as the response
body.
Express
• Express. js is the most popular backend framework for Node. js, and it
is an extensive part of the JavaScript ecosystem.
• It is designed to build single-page, multi-page, and hybrid web
applications, it has also become the standard for developing backend
applications with Node.
• Web Applications :
• Express is a minimal and flexible Node.js web application framework
that provides a robust set of features for web and mobile applications.
• APIs
• With a myriad of HTTP utility methods and middleware at your
disposal, creating a robust API is quick and easy.
• Performance
• Express provides a thin layer of fundamental web application features,
without obscuring Node.js features that you know and love.
• Frameworks
• Many popular frameworks are based on Express.
Middleware
• 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.
• An Express application can use the following types of middleware:
• Application-level middleware
• Router-level middleware
• Error-handling middleware
• Built-in middleware
• Third-party middleware
Application-level middleware
• Bind application-level middleware to an instance of the app object by using the
app.use() and app.METHOD() functions, where METHOD is the HTTP method of
the request that the middleware function handles (such as GET, PUT, or POST) in
lowercase.
• This example shows a middleware function with no mount path. The function is
executed every time the app receives a request.
• const express = require('express')
• const app = express()
• app.use((req, res, next) => {
• console.log('Time:', Date.now())
• next()
• })
Built-in middleware
• Starting with version 4.x, Express no longer depends on Connect. The
middleware functions that were previously included with Express are
now in separate modules; see the list of middleware functions.
• Express has the following built-in middleware functions:
• express.static serves static assets such as HTML files, images, and so
on.
• express.json parses incoming requests with JSON payloads. NOTE:
Available with Express 4.16.0+
• express.urlencoded parses incoming requests with URL-encoded
payloads. NOTE: Available with Express 4.16.0+
Third-party middleware
• Use third-party middleware to add functionality to Express apps.
• Install the Node.js module for the required functionality, then load it
in your app at the application level or at the router level.
• The following example illustrates installing and loading the cookie-
parsing middleware function cookie-parser.
• $ npm install cookie-parser
• const express = require('express')
• const app = express()
• const cookieParser = require('cookie-parser')

• // load the cookie-parsing middleware


• app.use(cookieParser())
Middleware module Description Replaces built-in function (Express 3)

body-parser Parse HTTP request body. See also: body, co-body, and raw-body. express.bodyParser

compression Compress HTTP responses. express.compress

connect-rid Generate unique request ID. NA

cookie-parser Parse cookie header and populate req.cookies. See also cookies and express.cookieParser
keygrip.

cookie-session Establish cookie-based sessions. express.cookieSession

cors Enable cross-origin resource sharing (CORS) with various options. NA

errorhandler Development error-handling/debugging. express.errorHandler

method-override Override HTTP methods using header. express.methodOverride


Writing middleware for use in
Express apps
• 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.
• Example:
• const express = require('express')
• const app = express()
• app.get('/', (req, res) => {
• res.send('Hello World!')
• })
• app.listen(3000)
The following figure shows the elements of a
middleware function call:

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.
Middleware function myLogger
• 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.
• const myLogger = function (req, res, next) {
• console.log('LOGGED')
• next()
•}
Configurable middleware

• If you need your middleware to be configurable, export a function which


accepts an options object or other parameters, which, then returns the
middleware implementation based on the input parameters.
• File: my-middleware.js
• module.exports = function (options) {
• return function (req, res, next) {
• // Implement the middleware function based on the options object
• next()
• }
•}
Middleware function requestTime
• we’ll create a middleware function called “requestTime” and add a
property called requestTime to the request object.
• const requestTime = function (req, res, next) {
• req.requestTime = Date.now()
• next()
• } The app now uses the requestTime middleware function. Also, the
callback function of the root path route uses the property that the
middleware function adds to req (the request object).
Middleware function validate
Cookies
• Finally, we’ll create a middleware function that validates incoming
cookies and sends a 400 response if cookies are invalid.
• Here’s an example function that validates cookies with an external async
service.
• async function cookieValidator (cookies) {
• try {
• await externallyValidateCookie(cookies.testCookie)
• } catch {
• throw new Error('Invalid cookies')
• }
•}

You might also like