如何在带有 nestjs 的路由中使用参数?

ale*_*uck 5 routes nestjs

我想使用 3 条路线:“项目”;'项目/1'; “项目/作者”。但是当我调用“项目/作者”时,触发了“项目/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));
        }

}
Run Code Online (Sandbox Code Playgroud)

Anr*_*nri 11

当你描述路线时你应该更加具体。

在这种情况下,路由无法理解哪个是路由路径,哪个是参数

你应该做 :

@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));
    }

}
Run Code Online (Sandbox Code Playgroud)

当您想获取单个项目时,请使用以下内容

@Get('/nameOfItem/:id')
Run Code Online (Sandbox Code Playgroud)

  • 我找到了另一个答案[github.com/nestjs/nest/issues](https://github.com/nestjs/nest/issues/995#issuecomment-415712163) (2认同)