文章目录
前言
中间件是在路由处理程序 之前 调用的函数。 中间件函数可以访问请求和响应对象,以及应用程序请求响应周期中的 next() 中间件函数。 next() 中间件函数通常由名为 next 的变量表示。
中间件函数可以执行以下任务:
- 执行任何代码。
- 对请求和响应对象进行更改。
- 结束请求-响应周期。
- 调用堆栈中的下一个中间件函数。
- 如果当前的中间件函数没有结束请求-响应周期, 它必须调用 next() 将控制传递给下一个中间件函数。否则, 请求将被挂起。
一、用中间件记录日志
官网例子:思路是当掉某个类下的接口的之前做log日志
比如想记录访问的ip与访问路径
//logger.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response, NextFunction } from 'express';
@Injectable()
export class LoggerMiddleware implements NestMiddleware {
use(req: Request, res: Response, next: NextFunction) {
console.log('Request...',req.host,req.originalUrl,req.body);
next();
}
}
//cats.controller.ts
import { Controller, Get, Header, Headers } from '@nestjs/common';
import { ApiHeader, ApiTags } from '@nestjs/swagger';
@Controller('cats')
@ApiTags('cats')
export class CatsController {
@Get('/aaa')
getHello(@Headers() params): string {
return '123213213';
}
@Get('/bbb')
getBbb(): string {
return '222222';
}
}
//app.module.ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { LoggerMiddleware } from './common/middleware/logger.middleware';
import { CatsModule } from './cats/cats.module';
@Module({
imports: [CatsModule],
})
export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer//访问cats下的接口之前打印log
.apply(LoggerMiddleware)
.forRoutes('cats');
}
}
此时访问cats下的路径就会在控制台打印ip与访问的路径
然后控制台就会打印
二、用全局拦截
如果我们想一次性将中间件绑定到每个注册路由,我们可以使用由INestApplication实例提供的 use()方法:
因为没有啥依赖关系,这里使用函数式中间件写法,
- data.middleware.ts
import { Request, Response, NextFunction } from 'express';
export function dataMiddleware(req: Request, res: Response, next: NextFunction) {
// if (req.url=='/bbb') {
// res.send('未登录')
// return
// }
console.log('Request...', req.url, req.body, req.query);
next();
}
以上就是基本使用方法,总之记着中间件是在路由处理程序 之前 调用的函数,就是调用后端接口之前做一些事情。