NestJs -应用中间件,不包含控制器的部分路由



我想只对控制器的部分路由应用中间件。我已经找了很长时间,但仍然没有找到解决办法

My controller code

在下面的代码中,我想应用中间件,不包括'/create'和'/login'路由。

@Controller('/driver')
export class DriversController {
constructor(private readonly service: DriversService, private readonly validator: DriverValidator) {}
@Post('/create')
async createDriver(@Body() driver: DriverDto): Promise<any> {
return this.service.createDriver(driver);
}
@Post('/login')
async loginDriver(@Body() body) {
await this.validator.validateDriverLoginInForm(body)
return this.service.loginDriver(body);
}
@Get('/get/products')
async getProducts(): Promise<any> {
return await this.service.getProducts();
}

我的中间件应用代码

export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.exclude() // what should I write here
.forRoutes(DriversController);
}
}

请帮帮我。I am new to nest js

请参阅NestJS提供的文档。它很好地解释了如何排除路由。

有两种方法可以做到这一点,一种是将路径添加到数组中,另一种是在数组中创建一个对象来定义路径和方法。当你有两个相同的路径,但有不同的请求方法时,后一个是有用的。

例子1:

exclude(['/driver/create', '/driver/login'])

和例2:

exclude(
[
{ 
path: '/driver/create', 
method: RequestMethod.POST 
}, 
{ 
path: '/driver/login', 
method: RequestMethod.POST 
}
]
)

但是由于您是NestJS的新手,这里是您的示例的开头:

export class AppModule implements NestModule {
configure(consumer: MiddlewareConsumer) {
consumer
.apply(LoggerMiddleware)
.exclude(
[
{
path: '/driver/create',
method: RequestMethod.POST
},
{
path: '/driver/login',
method: RequestMethod.POST
}
]
)
.forRoutes(DriversController);
}
}

让我知道它是否有效!

最新更新