用js徒手写一个中间键

2020-02-18 13:25:05 浏览数 (2)

什么是中间键? 下图中 C和D 的部分就是中间键

创建一个js文件 middleware.js 内容如下

代码语言:javascript复制
const App = () => {
  const req = {
    type: 'request',
    params: []
  }
  const res = {
    type: 'response'
  }

  const middlewares = []
  const use = fn => middlewares.push(fn)

  const runMiddlewares = index => {
    const count = middlewares.length
    if (index < count)
      middlewares[index].apply(null, [req, res, () => runMiddlewares(index   1)])
  }

  const get = (path, fn) => {
    runMiddlewares(0)
    fn.apply(null, [res, res])
  }

  return {
    get,
    use
  }
}

const app = App()
app.use((req, res, next) => {
  req.params.id = 5;
  console.log(req, 'request object accessed from middleware 1')
  console.log('Middleware 1')
  next()
})
app.use((req, res, next) => {
  console.log('Middleware 2')
  next()
})


app.use((req, res, next) => {
  console.log('Middleware 3')
  next()
})

app.get('/', (req, res) => {
  console.log('Response object accessd from get function')
})

执行这段代码

代码语言:javascript复制
node middleware.js

0 人点赞