Express ~ Middleware - rohit120582sharma/Documentation GitHub Wiki

In request-response model, web servers listen for requests, parse those requests, and send responses. The Node runtime will get these requests first and turn them from raw bytes into two JavaScript objects that you can handle: one object for the request (req) and one object for the response (res).

Express middleware are functions that execute during the lifecycle of a request to the Express server. Each middleware has access to the request object, response object, and the next function which points to the next middleware. Since the request and response object available, middleware is able to change these objects, run any code, pass control to next middleware function, or even end the request/response cycle.

In Node, these two objects are passed through just one function. But in Express, these objects are passed through an array of functions, called the middleware stack.

Middleware can handle tasks from logging requests to sending static files to setting HTTP headers.

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

Note: 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.




Application-level middleware

Bind application-level middleware to an instance of the app object by using the app.use() and app.METHOD() » app.get() functions, where METHOD is the HTTP method of the request that the middleware function handles (such as GET, PUT, or POST) in lowercase.

The path should match exactly, when using HTTP methods, for example app.get() or app.post() to handle the request.

To skip the rest of the middleware functions from a router middleware stack, call next('route') to pass control to the next route.

Note: next('route') will work only in middleware functions that were loaded by using the app.METHOD() or router.METHOD() functions.

const express = require('express');
const app = express();

// common middleare
app.use(function(req, res, next) {
    console.log('Time:', Date.now());
    next();
});

// method based middleware
app.get('/', function(req, res, next) {
    res.send('ROOT');
});
app.get('/user/:id', function(req, res, next) {
    res.send('USER');
});

// 404 handler middleware
app.use(function(req, res) {
    res.status(404).send('File not found!');
});


Router-level middleware

Routing is mapping different requests to different request handlers. In other word, it is a way to map requests to specific handlers depending on their URL and HTTP verb.

A router is an isolated instance of middleware and routes. Routers can be thought of as mini applications only capable of performing middleware and routing. Every express application has a built-in app router.

Routers can be used to split your application into many smaller applications that you can later put together.

Router-level middleware works in the same way as application-level middleware, except it is bound to an instance of express.Router().

In order to make the router work, the Router's instance needs to be registered with root router in this case app.


index.js

const birdsRouter = require('./birds');
app.use('/api/birds', birdsRouter);

birds.js

const express = require('express');
const router = express.Router();

/**
 * A middleware function with no mount path.
 * This code is executed for every request to the router
 */
router.use(function(req, res, next){
    console.log('Time:', Date.now());
    next();
});

/**
 * A middleware sub-stack that handles GET requests to the "/api/birds" and "/api/birds/about" path
 */
router.get('/', function (req, res, next) {
    res.send('BIRDS ROOT');
});
router.get('/about', function (req, res, next) {
    res.send('BIRDS ABOUT');
});

/**
 * A middleware sub-stack that handles GET/POST/DELETE requests to the "/api/birds:bird_id" path
 */
router.route('/birds/:bird_id')
    .all(function(req, res, next) {
        // runs for all HTTP verbs first
        next();
    })
    .get(function(req, res) {
        res.json(req.bird);
    })
    .post(function(req, res) {
        // create a new resource
    })
    .delete(function(req, res) {
        // delete the resource
    });

module.exports = router;


Error-handling middleware

When your app is in error mode, all regular middleware is ignored and Express will execute only error-handling middleware functions.

Define error-handling middleware functions in the same way as other middleware functions, except error-handling functions have four arguments instead of three: (err, req, res, next).

To enter error mode, simply call next with an argument next(new Error('Something bad happened!')).

app.get('/', function(req, res, next) {
    next(new Error('Something bad happened!'));
});
app.use(function(err, req, res, next) {
    console.log(err);
    res.status(500).send('Internal server error.');
});


Built-in middleware

var path = require('path');
var express = require('express');
var app = express();

// static files server middleware : serve static files
app.use('/assets', express.static(path.join(__dirname, 'public/assets')));

/**
 * parses incoming requests where Content-Type is application/x-www-form-urlencoded
 * <req.body> is populated with the parsed data
 */
app.use(express.urlencoded({ extended: true }));

/**
 * parses incoming requests where Content-Type is application/json
 * <req.body> is populated with the parsed data
 */
app.use(express.json());


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.

var express = require('express');
var app = express();
var morgan = require('morgan');
var cookieParser = require('cookie-parser');

// logger middleware : logs all incoming requests
app.use(morgan('short'));

// load the cookie-parsing middleware
app.use(cookieParser());
⚠️ **GitHub.com Fallback** ⚠️