中间件

分析

  • app.use 用来注册中间件,将中间件先收集起来
  • 遇到 http 请求,根据 path 和 method 判断处理那些
  • 实现next机制,即 指向下一个中间件

    原理

  • 通过代码说明 ```javascript const http = require(‘http’) const slice = Array.prototype.slice

class LikeExpress { constructor() { this.router = { all: [], // app.use() get: [], post: [] } }

  1. register(path) {
  2. const info = {}
  3. if (typeof path === 'string') {
  4. info.path = path
  5. // 从第二个参数开始取出,然后转换为数组
  6. info.stack = slice.call(arguments, 1)
  7. } else {
  8. info.path = '/'
  9. // 从第一个参数开始取出,然后转换为数组
  10. info.stack = slice.call(arguments, 0)
  11. }
  12. return info
  13. }
  14. use() {
  15. // 用apply 是因为函数中arguments是一个包含参数的类数组(并不是真正的数组)
  16. // 需要把它分成一个一个参数传下去
  17. const info = this.register.apply(this, arguments)
  18. this.router.all.push(info)
  19. }
  20. get() {
  21. const info = this.register.apply(this, arguments)
  22. this.router.get.push(info)
  23. }
  24. post() {
  25. const info = this.register.apply(this, arguments)
  26. this.router.post.push(info)
  27. }
  28. match(url, method) {
  29. let stack = []
  30. if(url === 'favicon.ico') {
  31. return stack
  32. }
  33. // 获取 路由
  34. const curRoutes = []
  35. curRoutes = curRoutes.concat(this.router.all)
  36. curRoutes = curRoutes.concat(this.router[method]) // 根据 method 区别
  37. // 根据 url 来区别
  38. curRoutes.forEach(routerInfo => {
  39. // 比如访问 /api/get-cookie
  40. if(url.indexOf(routerInfo.path) === 0) {
  41. // /
  42. // /api
  43. // /api/get-cookie
  44. stack = stack.concat(routerInfo.stack)
  45. }
  46. })
  47. return stack
  48. }
  49. // next 核心机制
  50. handle(req, res, stack) {
  51. const next = () => {
  52. const middleware = stack.shift()
  53. if(middleware) {
  54. middleware(req, res, next)
  55. }
  56. }
  57. next()
  58. }
  59. callback() {
  60. return (req, res) => {
  61. res.json = (data) => {
  62. res.setHeader('Content-Type', 'application/json')
  63. res.end(
  64. JSON.stringify(data)
  65. )
  66. }
  67. }
  68. const url = req.url
  69. const method = req.method.toLowerCase()
  70. const resultInfoList = this.match(url, method)
  71. // 处理 next 机制
  72. this.handle(req, res, resultInfoList)
  73. }
  74. listen(...args) {
  75. const server = http.createServer(this.callback())
  76. server.listen(...args)
  77. }

}

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()方法而言,第一个参数是作用域没有变化,变化的只是其余的参数都是直接传递给函数的。