SoFunction
Updated on 2025-03-10

Detailed explanation of two built-in middleware methods of Express framework

What is a middleware

Middleware is a function with series execution capabilities, middleware at two levels in Express. Middleware at the app level, Chinese-A pieces at the router level. In express, middleware is generally added through the use method and routing method.

Two built-in middleware

  • init middleware method
  • query middleware method

init method

 = function(app){
  return function expressInit(req, res, next){
    if (('x-powered-by')) ('X-Powered-By', 'Express');
     = res;
     = req;
     = next;
    setPrototypeOf(req, )
    setPrototypeOf(res, )
     =  || (null);
    next();
  };
};

expressInit middleware:

  • Set the 'X-Powered-By' request header
  • Add properties on req/res object
  • Bind prototype
  • Set local
  • Call next method

query middleware

 = function query(options) {
  var opts = merge({}, options)
  var queryparse = ;
  if (typeof options === 'function') {
    queryparse = options;
    opts = undefined;
  }
  if (opts !== undefined &&  === undefined) {
    // back-compat for qs module
     = true;
  }
  return function query(req, res, next){
    if (!) {
      var val = parseUrl(req).query;
       = queryparse(val, opts);
    }
    next();
  };
};

Returns a query function, and uses parseUrl and queryparse to process query in the url. At this point, query is maliciously used directly in req.

 = require('./middleware/query');

The query middleware is output and can be called manually.

Being used

 = function lazyrouter() {
  if (!this._router) {
    this._router = new Router({
      caseSensitive: ('case sensitive routing'),
      strict: ('strict routing')
    });
    this._router.use(query(('query parser fn')));
    this._router.use((this));
  }
};

Where the lazyrouter function is called, the use function is used to add middleware functions. Each app initialization will inject these two middleware.

summary

This article introduces the simple definition of middleware, which has concatenated features, as well as two built-in middleware in Express, one is the initial middleware of express and the other is the query middleware of express. The built-in query middleware is output and can be used externally and is initialized in it.

For more information about the built-in middleware of Express framework, please follow my other related articles!