Express中间件函数(Node.js)(3)
关于中间件函数的理解
多个中间件共享同一个res和req,所以可以在上游中间件中统一为res和req添加自定义的属性和方法,供下游的路由和中间件使用。
效果展示:
代码实现:
//导入express模块
const express = require('express');
const { send } = require('express/lib/response');
//实例化express对象
const app = express()
//创建中间件函数
app.use(function (req,res,next) {
//中间件函数的业务逻辑
console.log('中间件函数执行');
//获取时间
console.log(Date.now());
//重要一定要调用next()函数
next()
})
//路由函数
app.get('/user',(req,res)=>{
res.send('get请求成功')
})
//启动服务器
app.listen(8080,()=>{
console.log('服务器启动成功');
})
基本步骤:
(1),加载express模块
(2),实例化express对象
(3),使用app.use()创建中间件函数
app.use(function (req,res,next) {
//中间件函数的业务逻辑
console.log('中间件函数执行');
//获取时间
console.log(Date.now());
//重要一定要调用next()函数
next()
})
### 注意:
🥝_🥝重要重要
(1)中间件函数一定要在路由之前
(2)中间函数一定在函数体中,next()一下
(3)为防止代码逻辑混乱,不要再next()函数后写业务逻辑
(4)多个中间件共享同一个res和req
### 局部生效的中间写法
const mw = (req,res,next)=>{
console.log('局部生效的中间件函数')
next()
}
//路由函数
app.get('/user',mv,(req,res)=>{
res.send('get请求成功')
})
注意:
在路由哪里传一个中间件函数名。
小编:O_O