- 中间件实际上是在服务器接收到 HTTP 请求后、但在最终处理该请求并发送响应之前执行的一系列函数。
- 请求对象:
req,响应对象res - 通过调用
next()函数,中间件可以将控制权传递给下一个中间件函数,没有next的话,则该请求被挂起,实现拦截。 - 可以使用
next(err)将错误传递给专门的错误处理中间件。
路由
在请求到达最终路由处理程序之前对其进行拦截、修改或执行特定操作,接下来可以终止或者将控制权传递给下一个中间件函数或路由处理程序。 app.use() 定义全局中间件,所有请求先经过。
js
app.use(express.json());//先解析json才能在路由中访问json对象,也可链式调用use
app.use('/post', post);js
const express = require('express');
const app = express();
// 定义一个简单的中间件函数
const myMiddleware = (req, res, next) => {
console.log('中间件执行了!');
next(); // 调用 next() 函数以继续到下一个中间件或路由处理器
};
// 使用中间件
app.use(myMiddleware);
// 定义一个路由处理器
app.get('/', (req, res) => {
res.send('Hello, World!');
});
// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`服务器正在运行在 http://localhost:${PORT}`);
});为全部 http 方法应用路由规则
javascript
app.all('/secret', function (req, res, next) {
console.log('Accessing the secret section ...')
next() // pass control to the next handler
})捕获 params
Route path: /users/:userId/books/:bookId
Request URL: http://localhost:3000/users/34/books/8989
req.params: { "userId": "34", "bookId": "8989" }分词
Route path: /flights/:from-:to
Request URL: http://localhost:3000/flights/LAX-SFO
req.params: { "from": "LAX", "to": "SFO" }Route path: /plantae/:genus.:species
Request URL: http://localhost:3000/plantae/Prunus.persica
req.params: { "genus": "Prunus", "species": "persica" }中间件
类型:
- 全局中间件
- 局部中间件
- 错误中间件
内置中间件
express.static
- 是 Express 内置的一个中间件函数,用于托管静态文件,如 HTML 文件、CSS 文件、JavaScript 文件、图片等。
- 当使用
express.static中间件时,你需要指定一个根目录,该目录下的文件就可以通过Web访问。
- json 解析传入的 JSON 请求体
- urlencoded 解析传入的 URL 编码的数据(如果发送的是
x-www-form-urlencoded格式的数据)