【问题标题】:How to use parameters in routes with nestjs?如何在带有nestjs的路由中使用参数?
【发布时间】:2021-11-13 16:05:14
【问题描述】:

我想使用 3 条路线:“项目”; “项目/1”; “项目/作者”。 但是当我调用“project/authors”时,触发了“project/1”,我得到了一个错误。如何避免?

    @Controller('project')
    export class ProjectController {

        @Get()
        async getProjects(@Res() res): Promise<ProjectDto[]> {
            return await this.projectService.getProjects(0, 0).then(projects => res.json(projects));
        }
        @Get(':id')
        async getProject(@Param('id', new ParseIntPipe()) id, @Res() res): Promise<ProjectDto> {
            return await this.projectService.getProjects(id).then(project => res.json(project[0]));
        }

        @Get('/authors')
        async getAuthors(@Res() res): Promise<AuthorDto[]> {
            return await this.projectService.getAuthors().then(authors => res.json(authors));
        }

}

【问题讨论】:

    标签: routes nestjs


    【解决方案1】:

    您在描述路线时应该更加具体。

    在你的情况下,Routes 无法理解哪个是路由路径,哪个是参数

    你应该这样做:

    @Controller('project')
    export class ProjectController {
    
        @Get()
        async getProjects(@Res() res): Promise<ProjectDto[]> {
            return await this.projectService.getProjects(0, 0).then(projects => res.json(projects));
        }
        @Get('/project/:id')
        async getProject(@Param('id', new ParseIntPipe()) id, @Res() res): Promise<ProjectDto> {
            return await this.projectService.getProjects(id).then(project => res.json(project[0]));
        }
    
        @Get('/authors')
        async getAuthors(@Res() res): Promise<AuthorDto[]> {
            return await this.projectService.getAuthors().then(authors => res.json(authors));
        }
    
    }
    

    当您想获得单个项目时,请使用以下

    @Get('/nameOfItem/:id')
    

    【讨论】:

    【解决方案2】:

    事实上,在所有 express 应用中,所有路由的定义顺序都很重要。

    简单来说,先到先得,第一个匹配的路由就是用来响应你请求的路由。

    所以尽可能把静态参数放在第一位,然后是动态的。

    您唯一需要记住的是first come first serve :)

    【讨论】:

      猜你喜欢
      • 2018-10-30
      • 1970-01-01
      • 1970-01-01
      • 2022-06-29
      • 1970-01-01
      • 2014-04-28
      • 1970-01-01
      • 2021-01-15
      • 2020-12-12
      相关资源
      最近更新 更多