Node.js:express中间件1

114 阅读2分钟

express的中间件

中间件(Middleware),特指业务流程的中间处理环节

image.png

express中间件的调用流程

    当一个请求到达express的服务器之后,可以连续调用多个中间件,从而
对这次请求进行预处理 

image.png

express的中间件,本质上就是一个function处理函数,express中间件的格式如下:

image.png

next函数的作用

next函数是实现多个中间件连续调用的关键,它表示把流转关系转交给下一个中间件或路由(处理完毕,路由响应这次请求,路由为最终的处理环节)

定义中间件函数

    const express = require('express')
    const app = express()
    
    //常量mw所指向的,就是一个中间件函数
   const mw = function (req,res,next){
       console.log('这是一个最简单的中间件函数')
      //注意:在当前中间件的业务处理完毕后,必须调用next()函数
      //表示把流转关系转交给下一个中间件或路由
      next()
   }
   
   app.get('/',(req,res)=>{
       res.send('Home Page')
   })
   
   app.get('/user',(req,res)=>{
       res.send('User Page')
   })
   
   app.listen(80,()=>{
   console.log('http://127.0.0.1')
   })

全局生效的中间件

客户端发起的任何请求,到达服务器之后,都会触发的中间件,叫做全局生效的
中间件。

通过调用app.use(中间件函数),即可定义一个全局生效的中间件

    //方式1
    //常量mw所指向的,就是一个中间件函数
   const mw = function (req,res,next){
       console.log('这是一个最简单的中间件函数')
      //注意:在当前中间件的业务处理完毕后,必须调用next()函数
      //表示把流转关系转交给下一个中间件或路由
      next()
   }
   
   //全局生效的中间件
   app.use(mw)
    
    //方式2
    app.use(function(req,res,next){
        console.log('这是一个最简单的中间件函数')
        next()
    })

中间件的作用

多个中间件之间,共享同一份req和res,基于这样的特性,我们可以在上游的
中间件中,统一为req或res对象添加自定义的属性或方法,供下游的中间件或
路由进行使用

需求假设:打印每个url请求的时间

不使用中间件

    const express = require('express')
    const app = express()
    
    app.get('/',(req,res)=>{
        const time = Date.now()
        res.send('Home Page',time)
    })
    app.get('/user',(req,res)=>{
        const time = Date.now()
        res.send('User name',time)
    })
    
    app.listen(80,()=>{
        console.log('http://127.0.0.1')
    })

使用中间件

    const express = require('express')
    const app = express()
    
    app.use((req,res,next)=>{
        //获取到请求到达服务器的时间
        const time = Date.now()
        //为req对象,挂载自定义属性,从而把时间共享给后面的所有路由
        req.stareTime = time
        next()
    })
    app.get('/',(req,res)=>{
        res.send('Home Page',req.startTime)
    })
    app.get('/user',(req,res)=>{
        res.send('User name',req.startTime)
    })
    
    app.listen(80,()=>{
        console.log('http://127.0.0.1')
    })

定义多个中间件

可以使用app.use()连续定义多个全局中间件,客户端请求到达服务器后,会按照中间件定义的
先后顺序依次进行调用.