中间件机制的核心实现
中间件是从Http请求发起到响应结束的处理方法。通常需要处理请求和响应,所以一个基本的中间件是以下形式:
const middleware = (req, res, next) => { // TODO next()} 模拟最基本的中间件 // 定义三个简单的中间件 const httpMeth1 = (req, res, next) => { console.log ('我请求 1') next() } const httpMeth2 = (req, res, next) => { console.log('我请求 2') next() } const httpMeth3 = (req, res, next) => { console.log('我是请求 3') next() } // 中间件数组 const allHttpMeth = [httpMeth1, httpMeth2, httpMeth3] function run (req, res) { const next = () => { //获取中间件 const allHttpMethitem = allHttpMeth.shift() if (allHttpMethitem) { // 执行 allHttpMethitem(req, res, next) } } next() } run() // 模拟请求发起
if 中有异步操作中间件,异步操作过程结束后需要调用next()方法,否则中间件无法顺序执行
《nodejs视频教学》