乐闻世界logo
搜索文章和话题

How to create nested routes with parameters using NestJS

1个答案

1

In NestJS, creating nested routes with parameters involves several key steps, primarily defining route decorators within controllers. Here is an example of the steps to implement nested routes with parameters:

  1. Define Parent Module Route: First, create the parent module's controller and use the @Controller decorator to define the parent route.
typescript
import { Controller, Get } from '@nestjs/common'; @Controller('parent') export class ParentController { @Get() getAllParents() { return 'All parent module data'; } }
  1. Define Child Module Route: Create the child module's controller and define routes within it, using the @Controller decorator to specify the child route path.
typescript
import { Controller, Get, Param } from '@nestjs/common'; @Controller('children') export class ChildrenController { @Get() getAllChildren() { return 'All child module data'; } @Get(':id') getChildById(@Param('id') id: string) { return `Child module data ${id}`; } }
  1. Implement Nested Routes: Nest the child module controller within the parent module controller by using a route path prefix to achieve nesting.
typescript
import { Controller, Get, Param } from '@nestjs/common'; @Controller('parent/:parentId/children') export class ChildrenController { @Get() getChildrenByParent(@Param('parentId') parentId: string) { return `All child module data for parent ${parentId}`; } @Get(':childId') getChildByParent( @Param('parentId') parentId: string, @Param('childId') childId: string ) { return `Child module data ${childId} for parent ${parentId}`; } }

In the above code, we define nested routes under the parent module parent for the child module children, enabling access to specific data via paths like /parent/123/children/456, where 123 is the parent module ID and 456 is the child module ID.

The above steps demonstrate how to create nested routes with parameters in NestJS. Route parameters in controllers are retrieved using the @Param decorator, enabling dynamic and flexible handling of routes. This nested routing design allows organizing API endpoints by resources and relationships, thereby improving code readability and maintainability.

2024年6月29日 12:07 回复

你的答案