把中间件用起来:中间件是三参数工具,使用需要修改AppModule的configure,加入consumer来apply和forRoutes,这里应该是可以给数组,用来对多个路由进行处理吧
This commit is contained in:
		
							parent
							
								
									bf25cd7eaa
								
							
						
					
					
						commit
						41e876acd6
					
				| 
						 | 
				
			
			@ -1,11 +1,16 @@
 | 
			
		|||
import { Module } from '@nestjs/common';
 | 
			
		||||
import { Module, NestModule, MiddlewareConsumer} from '@nestjs/common';
 | 
			
		||||
import { AppController } from './app.controller';
 | 
			
		||||
import { AppService } from './app.service';
 | 
			
		||||
import { PostsModule } from './modules/posts/posts.module';
 | 
			
		||||
import { DemoMiddleware } from './core/middleware/demo.middleware'
 | 
			
		||||
 | 
			
		||||
@Module({
 | 
			
		||||
  imports: [PostsModule],
 | 
			
		||||
  controllers: [AppController],
 | 
			
		||||
  providers: [AppService],
 | 
			
		||||
})
 | 
			
		||||
export class AppModule {}
 | 
			
		||||
export class AppModule implements NestModule {
 | 
			
		||||
  configure(consumer: MiddlewareConsumer) {
 | 
			
		||||
    consumer.apply(DemoMiddleware).forRoutes('posts')
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
| 
						 | 
				
			
			@ -3,6 +3,7 @@ import { Injectable, NestMiddleware } from '@nestjs/common';
 | 
			
		|||
@Injectable()
 | 
			
		||||
export class DemoMiddleware implements NestMiddleware {
 | 
			
		||||
  use(req: any, res: any, next: () => void) {
 | 
			
		||||
    console.log('hello ~')
 | 
			
		||||
    next();
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
| 
						 | 
				
			
			
 | 
			
		|||
		Loading…
	
		Reference in New Issue