说说nodejs中间件是什么,如何封装一个中间件
# 是什么
在nodejs中,中间件本质是一个回调函数,参数包括了请求对象,响应对象和执行下一个中间件的next函数
foo(ctx, next)
# 怎么用
- 日志模块
module.exports = async (ctx, next) =>{
const startTime = Date.now()
const requestTime = new Date()
await next()
const ms = Date.now() - startTime
let logout = `${ctx.request.ip}---${requestTime} -- ${ctx.method} --${ctx.url}--${ctx.ms}ms`
fs.appendFileSync('./log.txt', logout+'\n')
}
- token校验
module.exports = async (ctx, next) => {
const token = ctx.header.token
if(token){
try{
await verify(token)
}catch(err){
throw err
}
}
await next()
}
# 原理
中间件应职责单一,应有扩展性和组合性
# FAQ
上次更新: 2021/12/19, 18:05:42