Home > other >  Nest JS: how to define multiple endpoints in a single controller?
Nest JS: how to define multiple endpoints in a single controller?

Time:07-27

Is there a way to define multiple endpoints inside a single controller? It is described in the documentation: https://docs.nestjs.com/controllers#routing...

...Since we've declared a prefix for every route ( cats), and haven't added any path information in the decorator, Nest will map GET /cats requests to this handler. As mentioned, the path includes both the optional controller path prefix and any path string declared in the request method decorator. For example, a path prefix of customers combined with the decorator @Get('profile') would produce a route mapping for requests like GET /customers/profile

How do I define a controller with multiple endpoints?

I want:

/ /dogs /fish

and Im trying to achieve this with

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) { }

  @Get()
  getHello(): string {
    return "<h1>AppController @Get (root URL) working</h1>";
  }

  @Get('dogs')
  getHello(): string {
    return "<h1>AppController @Get dogs working</h1>";
  }

  @Get('fish')
  getHello(): string {
    return "<h1>AppController @Get fish working</h1>";
  }
}

The problem with this is only the last @Get decorated function is accessible. i.e. whichever endpoint i shuffle to the end of this codeblock is the only one accessible through the browser address bar.

CodePudding user response:

Because your implementation has functions with identical names that end up in the internal registry under the same key

CodePudding user response:

The function name is significant despite the fact the docs say it can be anything, it has to be unique. This works:

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) { }

  @Get('fish')
  getFish(): string {
    return "<h1>AppController @Get fish working</h1>";
  }

  @Get('dogs')
  getDogs(): string {
    return "<h1>AppController @Get dogs working</h1>";
  }

  @Get()
  getHello(): string {
    return this.appService.getHello();
  }
}
  • Related