Express 的中间件

使用 express 处理请求的时候,一般都在后面添加个回调,每个回调都包含req、res和next。而这一个个回调函数就是我们要学的中间件。

利用中间件我们可以做什么事情呢?

  1. 执行这任意代码。
  2. 更改请求对象和响应对象。
  3. 结束请求-响应周期。
  4. 调用堆栈中的下一个中间件函数。

如果当前中间件函数没有结束请求-响应周期,它必须调用 next() 将控制传递给下一个中间件函数。否则,请求将被挂起。

下图显示了中间件函数调用的元素:

从Express 5开始,返回 Promise 的中间件函数将在 reject 或抛出错误时调用 next(value)。next 将被调用,并返回被拒绝的值或抛出的错误。

关于中间的分类有哪些呢?

  1. 应用层的中间件:其实我们可以写包含req、res和next的一个函数,然后通过app.use注册一下,这样它就算一个应用层的中间件了。在请求处理的过程中,它就会被执行。
  2. 路由器级中间件:Express 的路由
  3. 错误处理中间件:Express 的错误处理
  4. 内置中间件:例如express.json()、express.urlencoded()等
  5. 第三方中间件:社区下载的中间件

不管分多少类,本质上都是包含req、res和next的回调。

关于中间件的调用,它永远先调用第一个匹配的中间件,调用完成后,看有没有next()去连接下一个中间件,没有的话就挂起,有就一直执行下去。

连续使用中间件的时候,通常把响应放在最后一个中间件。

javascript 复制代码
const express = require('express');
const app = express();
const port = 3000;

const middleware1 = (req, res, next) => {
    console.log('middleware1')
    next()
}
const middleware2 = (req, res, next) => {
    console.log('middleware2')
    next()
}
const middleware3 = (req, res, next) => {
    console.log('middleware3')
    next()
}

app.use(middleware1)
app.use(middleware2)
app.use(middleware3)

app.get('/', function (req, res, next) {
    console.log('express')
    res.json('express')
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

// 打印结果
middleware1
middleware2
middleware3
express

如果我想往请求里添加参数,怎么做?

javascript 复制代码
const express = require('express');
const app = express();
const port = 3000;

const middleware = (req, res, next) => {
    req.name = 'jiawei'
    req.age = 18
    next()
}

app.use(middleware)

app.get('/info', function (req, res, next) {
    console.log('req.name:', req.name)
    console.log('req.age:', req.age)
    res.json('express')
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

Postman请求 localhost:3000/info,打印结果

javascript 复制代码
req.name: jiawei
req.age: 18

如果是只想往特定的请求里添加数据呢?

javascript 复制代码
const express = require('express');
const app = express();
const port = 3000;

const middleware = (req, res, next) => {
    req.name = 'jiawei'
    req.age = 18
    next()
}

// app.use(middleware)

app.get('/info', function (req, res, next) {
    console.log('req.name:', req.name)
    console.log('req.age:', req.age)
    res.json('express')
})

app.get('/user', middleware, function (req, res, next) {
    console.log('req.name:', req.name)
    console.log('req.age:', req.age)
    res.json('express')
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

这时,Postman 请求 localhost:3000/info,结果如下

javascript 复制代码
req.name: undefined
req.age: undefined

而 Postman 请求 localhost:3000/user,结果如下

javascript 复制代码
req.name: jiawei
req.age: 18
相关推荐
阿珊和她的猫2 小时前
v-scale-scree: 根据屏幕尺寸缩放内容
开发语言·前端·javascript
fouryears_234174 小时前
Flutter InheritedWidget 详解:从生命周期到数据流动的完整解析
开发语言·flutter·客户端·dart
我好喜欢你~5 小时前
C#---StopWatch类
开发语言·c#
加班是不可能的,除非双倍日工资6 小时前
css预编译器实现星空背景图
前端·css·vue3
lifallen6 小时前
Java Stream sort算子实现:SortedOps
java·开发语言
IT毕设实战小研6 小时前
基于Spring Boot 4s店车辆管理系统 租车管理系统 停车位管理系统 智慧车辆管理系统
java·开发语言·spring boot·后端·spring·毕业设计·课程设计
wyiyiyi7 小时前
【Web后端】Django、flask及其场景——以构建系统原型为例
前端·数据库·后端·python·django·flask
gnip7 小时前
vite和webpack打包结构控制
前端·javascript
excel7 小时前
在二维 Canvas 中模拟三角形绕 X、Y 轴旋转
前端
cui__OaO8 小时前
Linux软件编程--线程
linux·开发语言·线程·互斥锁·死锁·信号量·嵌入式学习