【问题标题】:How to exclude all routes except one in NestJs?如何在 NestJs 中排除除一条以外的所有路线?
【发布时间】:2022-03-09 22:41:02
【问题描述】:

假设我有两个路由的控制器:

@Controller('events')
export class EventController {

    @Get('my')
    async getMyEvents() {
        return "A"
    }

    @Get(':eventId')
    async getEvent(@Param('eventId', ParseUUIDPipe) eventId: string) {
        return "B"
    }
}

我需要排除所有路线,除了有参数的路线:

export class EventModule implements NestModule {
    configure(consumer: MiddlewareConsumer) {
        consumer
            .apply(AuthMiddleware)
            .exclude({path: 'api/events/:eventId', method: RequestMethod.GET})
            .forRoutes(EventController)
    }
}

但它不起作用,它还排除了路由api/events/my,那么如何避免呢?

【问题讨论】:

  • 为什么不使用forRoutes 专门用于您想要到达的路线?或者为什么不使用拦截器/守卫呢?
  • 因为实际上我有很多路线,所以在forRoutes中列出所有路线会很不方便
  • 您可能会使用正则表达式而不是直接路径。类似new RegExp('api\/events\/[^me]*')

标签: express nestjs


【解决方案1】:

在exclude中添加你想要排除的路由,其余的在forRoutes中

导出类 EventModule 实现 NestModule { 配置(消费者:中间件消费者){ 消费者 .apply(AuthMiddleware) 。排除(”*”) .forRoutes({path: 'api/events/:eventId', 方法: RequestMethod.GET}) } }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-01-05
    • 2013-06-10
    • 1970-01-01
    • 2020-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-24
    相关资源
    最近更新 更多