Nest.js - Middleware

2020-07-10  本文已影响0人  stevekeol
中间件的介绍

中间件函数可以执行以下任务:

自定义中间件的实现
//logger.middleware.ts
import { Injectable, NestMiddleware } from '@nestjs/common';
import { Request, Response } from 'express';

@Injectable()
export class LoggerMiddleware implements NestMiddleware {
  use(req: Request, res: Response, next: Function) {
    console.log('Request...');
    next();
  }
}
中间件的应用
import { Module, NestModule, MiddlewareConsumer } form '@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
      .apply(LoggerMiddleware)
      .forRoutes('cats'); //  在限定的'/cats'路由路径下的处理程序中设置了LoggerMiddleware
  }
}
import { Module, NestModule, RequestMethod, 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
      .apply(LoggerMiddleware)
      .forRoutes({ path: 'cats', method: RequestMethod.GET });
  }
}
forRoutes({ path: 'ab*cd', method: RequestMethod.ALL });
中间件消费者
//app.module.ts - 单个控制器类(CatsController)
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { LoggerMiddleware } from './common/middleware/logger.middleware';
import { CatsModule } from './cats/cats.module';
import { CatsController } from './cats/cats.controller.ts';

@Module({
  imports: [CatsModule],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply(LoggerMiddleware)
      .forRoutes(CatsController);
  }
}
// 对CatsController中所有注册的路由(除了exclude()标注的之外)使用中间件LoggerMiddleware
consumer
  .apply(LoggerMiddleware)
  .exclude(
    { path: 'cats', method: RequestMethod.GET },
    { path: 'cats', method: RequestMethod.POST },
    'cats/(.*)',
  )
  .forRoutes(CatsController);
函数式中间件
//中间件的定义: logger.middleware.ts
export function logger(req, res, next) {
  console.log(`Request...`);
  next();
};
//中间件的使用: app.module.ts
consumer
  .apply(logger)
  .forRoutes(CatsController);
多个中间件
consumer.apply(cors(), helmet(), logger).forRoutes(CatsController);
全局中间件
const app = await NestFactory.create(AppModule);
app.use(logger);
await app.listen(3000);
上一篇 下一篇

猜你喜欢

热点阅读