【问题标题】:How to deal with NestJS @Get() decorator?如何处理 NestJS @Get() 装饰器?
【发布时间】:2021-11-14 10:07:57
【问题描述】:

这段代码可以正常工作。我可以使用 URL 访问这两个功能 http://localhost:3000/vehicle/availableVehicles & http://localhost:3000/vehicle/1 相应

    @Controller('vehicle')
    export class VehicleController {
        constructor(
            private readonly vehicleService: VehicleService,
            private readonly crudService: CurdService
        ) { }
        tableName: string = 'vehicle';
    
        @Get('availableVehicles')
        async availableVehicles() {
            return await this.vehicleService.availableVehicles();
        }
        
        @Get(':id')
        async getbyId(@Req() request: Request) {
            return await this.crudService.getById(this.tableName, request.params.id);
        }
  }

但是当我只是在下面的代码块之类的两个函数之间进行交换时,函数 availableVehicles() 不起作用和 URL http://localhost:3000/vehicle/availableVehicles 点击getbyId() 函数。该怎么办?还是我做错了什么?提前致谢。

    @Controller('vehicle')
    export class VehicleController {
        constructor(
            private readonly vehicleService: VehicleService,
            private readonly crudService: CurdService
        ) { }
        tableName: string = 'vehicle';

        @Get(':id')
        async getbyId(@Req() request: Request) {
            return await this.crudService.getById(this.tableName, request.params.id);
        }
    
        @Get('availableVehicles')
        async availableVehicles() {
            return await this.vehicleService.availableVehicles();
        }
  }

【问题讨论】:

标签: javascript node.js express nestjs


【解决方案1】:

您只需完全按照第一个示例中所做的操作,将更具体的路由放在带有路由参数的路由之上。

当应用程序启动时正在构建服务器的路由表时,它们将按此顺序被发现和注册。

这是https://stackoverflow.com/a/68727403/1364771的副本

【讨论】:

  • 谢谢并接受您的回答,但有没有其他方法可以让我不必考虑订购?
  • 不,不可能。两条路线都匹配,它应该如何确定使用哪一条?它不能同时使用两者,因此您作为开发人员需要提供一个“决胜局”。目前这只能通过路由定义的排序来完成。
猜你喜欢
  • 2021-10-25
  • 1970-01-01
  • 1970-01-01
  • 2018-07-27
  • 1970-01-01
  • 2019-10-01
  • 2021-12-28
  • 2020-06-26
  • 2016-12-01
相关资源
最近更新 更多