express中间件

119 阅读2分钟

中间件

中间件本质是一个回调函数; 中间件函数可以像路由回调一样访问请求对象(request), 响应对象(response)

一. 中间件作用

中间件的作用, 使用函数封装公共操作, 简化代码

二. 中间件类型

  • 全局中间件
  • 路由中间件
  1. 定义全局中间件

    每个请求到达服务器之后都会执行全局中间件

    //1.导入express模块
    const express = require('express')
    const fs = require('fs')
    const path = require('path')
    ​
    //2.创建应用对象
    const app = express()
    ​
    //声明中间件函数
    function recordMiddleware(req,res,next){
      // 获取url和ip
      let {url,ip} = request
      //保存信息到record.txt
      fs.appendFileSync(path.resolve(__dirname,'./record.txt'),`${url} ${ip}\n`)
    ​
      next()
    ​
    }
    ​
    //使用中间件函数
    //app.use()是专门解析中间件函数的方法, 使用之后express会将http请求响应对象交给中间件函数, 中间件函数处理完通过next()方法传递给下一个中间件函数, 直到返回响应数据
    app.use(recordMiddleware)
    ​
    //3.创建路由
    app.get('/home',(request,response)=>{
      response.send('前端页面')
    })
    ​
    app.get('/admin',(request,response)=>{
      response.send('后台页面')
    })
    ​
    //4.监听路由, 启动服务
    app.listen(3000,()=>{
      console.log('服务启动成功')
    })
    

    app.use()是专门解析中间件函数的方法, 使用之后express会将http请求响应对象交给中间件函数, 中间件函数处理完通过next()方法传递给下一个中间件函数, 直到返回响应数据

  2. 定义路由中间件

    /**
     * 针对 /admin /setting 的请求, 要求URL携带code=521参数, 如果未携带提示[暗号错误]
     *///1.导入express模块
    const express = require('express')
    ​
    //2.创建应用对象
    const app = express()
    ​
    //创建路由中间件
    let checkCodeMiddleware = (req, res, next) => {
      if(req.query.code === '521'){
        next()
      }else{
        res.send('暗号错误')
      }
    }
    ​
    //3.创建路由
    app.get('/admin', checkCodeMiddleware, (req, res) => {
      res.send('后端首页')
    })
    ​
    app.get('/setting', checkCodeMiddleware, (req, res) => {
      res.send('后端设置')
    })
    ​
    //4.监听路由,开启服务
    app.listen('3000', () => {
      console.log('服务启动成功')
    })
    
  3. 静态资源中间件

    //1.导入express模块
    const express = require('express')
    ​
    //2.创建应用对象
    const app = express()
    ​
    //静态资源中间件设置
    app.use(express.static(__dirname + '/public'))
    ​
    ​
    //3.创建路由
    app.get('/index', (req, res) => {
      res.send('你好')
    })
    ​
    //4.监听路由,启动服务
    app.listen(3000, () => {
      console.log('服务启动成功')
    })
    
    • index.html文件为默认打开的资源
    • 如果静态资源和路由规则同时匹配, 谁在前先响应谁
    • 路由响应动态资源, 静态资源中间件响应静态资源