中间件
分析
- app.use 用来注册中间件,将中间件先收集起来
- 遇到 http 请求,根据 path 和 method 判断处理那些
-
原理
通过代码说明 ```javascript const http = require(‘http’) const slice = Array.prototype.slice
class LikeExpress { constructor() { this.router = { all: [], // app.use() get: [], post: [] } }
register(path) {const info = {}if (typeof path === 'string') {info.path = path// 从第二个参数开始取出,然后转换为数组info.stack = slice.call(arguments, 1)} else {info.path = '/'// 从第一个参数开始取出,然后转换为数组info.stack = slice.call(arguments, 0)}return info}use() {// 用apply 是因为函数中arguments是一个包含参数的类数组(并不是真正的数组)// 需要把它分成一个一个参数传下去const info = this.register.apply(this, arguments)this.router.all.push(info)}get() {const info = this.register.apply(this, arguments)this.router.get.push(info)}post() {const info = this.register.apply(this, arguments)this.router.post.push(info)}match(url, method) {let stack = []if(url === 'favicon.ico') {return stack}// 获取 路由const curRoutes = []curRoutes = curRoutes.concat(this.router.all)curRoutes = curRoutes.concat(this.router[method]) // 根据 method 区别// 根据 url 来区别curRoutes.forEach(routerInfo => {// 比如访问 /api/get-cookieif(url.indexOf(routerInfo.path) === 0) {// /// /api// /api/get-cookiestack = stack.concat(routerInfo.stack)}})return stack}// next 核心机制handle(req, res, stack) {const next = () => {const middleware = stack.shift()if(middleware) {middleware(req, res, next)}}next()}callback() {return (req, res) => {res.json = (data) => {res.setHeader('Content-Type', 'application/json')res.end(JSON.stringify(data))}}const url = req.urlconst method = req.method.toLowerCase()const resultInfoList = this.match(url, method)// 处理 next 机制this.handle(req, res, resultInfoList)}listen(...args) {const server = http.createServer(this.callback())server.listen(...args)}
}
module.exports = () => { return new LikeExpress() } ```
注 call bind apply 用法
- call 、bind 、 apply 这三个函数的第一个参数都是 this 的指向对象
- call 的参数是直接放进去的,第二第三第 n 个参数全都用逗号分隔,比如obj.myFun.call(db,’成都’, … ,’string’
- apply 的所有参数都必须放在一个数组里面传进去,比如obj.myFun.apply(db,[‘成都’, …, ‘string’ ])
- bind 除了返回是函数以外,它 的参数和 call 一样
- Array.prototype.slice.apply 用法
- call()方法与apply()方法的作用相同,它们的区别仅在于接收参数的方式不同。对于call()方法而言,第一个参数是作用域没有变化,变化的只是其余的参数都是直接传递给函数的。
