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
相关推荐
iCxhust9 分钟前
Prj10--8088单板机C语言8259测试(1)
c语言·开发语言
kite01213 小时前
浏览器工作原理06 [#]渲染流程(下):HTML、CSS和JavaScript是如何变成页面的
javascript·css·html
крон3 小时前
【Auto.js例程】华为备忘录导出到其他手机
开发语言·javascript·智能手机
zh_xuan4 小时前
c++ 单例模式
开发语言·c++·单例模式
老胖闲聊4 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1184 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之5 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
豆沙沙包?5 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏
军训猫猫头5 小时前
96.如何使用C#实现串口发送? C#例子
开发语言·c#
coding随想5 小时前
JavaScript ES6 解构:优雅提取数据的艺术
前端·javascript·es6