Node.js服务端之express系统过一下-02-中间件

56 阅读2分钟

中间件:中间件就是一个可以访问请求对象、响应对象和调用next方法的一个函数,不用修改自己的代码,以此来扩展或者处理一些功能,一个express应用就是由一个个中间件构成,中间件可以共享请求和响应对象。

基本写法

app.use((req, res) => {
  console.log(new Date());
})

此时发送请求会卡住,因为没有允许下一步的执行

需要使用next


const express = require('express')

const app = express()

app.use((req, res, next) => {
  console.log(new Date());
  // 交出执行权 继续往后匹配
  next()
})

app.get('/', (req, res) => {
  res.send('///')
  console.log('///');
})

app.listen(5566, () => {
  console.log('已运行在5566上');
})

应用级中间件

不关心请求路径

应用内所有的请求都经过的中间件

app.use((req, res, next) => {
  console.log(new Date());
  // 交出执行权 继续往后匹配
  next()
})

限定请求路径

只有指定路径请求,才会经过的中间件

app.use('/',(req, res, next) => {
  console.log(new Date());
  // 交出执行权 继续往后匹配
  next()
})

多个处理函数

应用级中间件可以配置多个处理函数,基本写法如下

app.use('/',
  (req, res, next) => {
    console.log(new Date());
    // 交出执行权 继续往后匹配
    next()
  },
  (req, res, next) => {
    console.log(req.params);
    // 交出执行权 继续往后匹配
    next()
  }
)

路由级别中间件

路由实例其实就相当于一个小的 Express实例,先写一个基本路由

const express = require('express')


// 1.创建路由实例
// 路由实例其实就相当于一个小的 Express实例

const router = express.Router()
// 2.配置路由
router.get('/good', (req, res) => {
  res.send('get /good')
})

router.get('/bad', (req, res) => {
  res.send('get /bad')
})

// 3.导出路由实例
module.exports = router
// 挂载路由
app.use(router)

给路由限定前缀,必须以前缀加路由

// 给路由限定前缀
app.use('test', router)

错误处理中间件

在所有中间件之后的挂载错误处理中间件,有4个参数,错误对象、请求对象、响应对象、next对象

基本定义

app.use((err, req, res, next) => {
  console.log('错误' + err);
  res.status(500).json({
    error: err.message
  })
})

使用

app.get('/', (req, res, next) => {
  try {
    res.send('///')
    console.log('///');
  } catch (err) {
    next(err)
  }

})

处理404

通常在所有路由之后 配置处理 404,程序会顺序匹配,匹配到此发送找不到

// 通常在所有路由之后 配置处理 404
app.use((req, res, next) => {
  res.status(404).send('404 找不到了啦')
})