express
基于 Node.js
平台,快速、开放、极简的 Web
开发框架
中间件
从请求到相应过程中执行的一系列函数被称为中间件,使其具有了极高的扩展性
注册
1 2 3 4 5 6 7
| app.use(function middware1(req, res, next) { })
app.use('/test', function middware2(req, res, next) { })
|
使用
当请求 /test
时,会按照 middware1
-> middware2
的顺序依次执行注册的中间件
简易实现
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| function isMathch(source, match) { return source.startsWith(match) }
const express = { middwares: [], use: function (path, fun) { let handler = fun let matchPath = path if (typeof fun === 'undefined') { matchPath = '/' handler = path } this.middwares.push({ handler, path: matchPath }) }, call: function (req, res) { const { pathname = '/' } = req const middwares = this.middwares.filter((item) => isMathch(pathname, item.path) ) const len = middwares.length let index = -1
function next(err) { index++ if (index < len) { middwares[index].handler(req, res, next) } }
return next() }, }
|
- express 调度实现链接
- express use 实现链接
参考