什么是中间键? 下图中 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