In NodeJs, middleware primarily refers to methods that encapsulate all the details of Http request processing. An Http request usually involves a lot of work, such as logging, IP filtering, query string, request body parsing, Cookie handling, permission validation, parameter validation, exception handling, etc., but for Web applications, you don’t want to have to deal with so much detail processing. Therefore, middleware is introduced to simplify and isolate the details between so much infrastructure and business logic, so that developers can focus on business development to achieve the purpose of improving development efficiency.

Middleware behaves similar to how filters work in Java, in that they are processed before entering the specific business process.

const http = require('http')
function compose(middlewareList) {
  return function (ctx) {
    function dispatch(i) {
      const fn = middlewareList[i]
      try {
        return Promise.resolve(fn(ctx, dispatch.bind(null, i + 1)))}catch (err) {
        Promise.reject(err)
      }
    }
    return dispatch(0)}}class App {
  constructor() {
    this.middlewares = []
  }
  use(fn) {
    this.middlewares.push(fn)
    return this
  }
  handleRequest(ctx, middleware) {
    return middleware(ctx)
  }
  createContext(req, res) {
    const ctx = {
      req,
      res
    }
    return ctx
  }
  callback() {
    const fn = compose(this.middlewares)
    return (req, res) = > {
      const ctx = this.createContext(req, res)
      return this.handleRequest(ctx, fn)
    }
  }
  listen(. args) {
    const server = http.createServer(this.callback())
    returnserver.listen(... args) } }module.exports = App
Copy the code