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

How to use parameters in routes with nestjs?

我想使用 3 条路线:‘project’; 'project/1'; 'project/authors'。 但是当我调用‘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));
        }

}

你在描述路线的时候应该更具体。

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

你应该这样做:

@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')

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

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

所以尽量先静态参数再动态参数。

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