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

How to add a route prefix to specific modules using NestJS?

1个答案

1

Adding route prefixes to specific modules in NestJS is a straightforward process. This is typically achieved by setting the controllers property within the @Module decorator of the module. To add prefixes to all controllers under a specific module, use the @Controller decorator at the module level and specify the prefix within it. Below are the steps to follow:

  1. Import the Module and Controller decorators:
typescript
import { Module, Controller } from '@nestjs/common';
  1. Use the @Controller decorator in the module's controller and specify the route prefix:
typescript
@Controller('prefix') export class YourController { // ... }

In the above code, 'prefix' is the route prefix set for this controller. This means that if your controller has a route decorator like @Get('example'), the final route will be /prefix/example.

  1. Of course, you can also set a prefix at the module level to automatically apply it to all controllers registered within the module. First, ensure your module is defined using the @Module decorator, like this:
typescript
@Module({ controllers: [YourController], // ... (other properties like providers, exports, etc.) }) export class YourModule {}
  1. Next, to add route prefixes to all controllers within the entire module, utilize the module class's constructor and the setGlobalPrefix method. For example, you can do this in the main.ts file:
typescript
import { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; async function bootstrap() { const app = await NestFactory.create(AppModule); app.setGlobalPrefix('api'); await app.listen(3000); } bootstrap();

The above code sets a global prefix api for all routes in the application. However, if you only want to set a prefix for a specific module rather than globally, do not use the setGlobalPrefix method.

  1. For setting prefixes on specific modules, create a base controller class that uses the @Controller decorator to add the prefix, and have all controllers within the module inherit this base controller.

Example:

typescript
@Controller('modulePrefix') export class BaseModuleController {} export class ActualController extends BaseModuleController { @Get('example') exampleMethod() { // ... } }

In this example, ActualController inherits from BaseModuleController, meaning all routes defined in ActualController automatically include the modulePrefix prefix. Therefore, the final route for the exampleMethod method is /modulePrefix/example.

By following these steps, you can effectively add route prefixes to specific modules in your NestJS application to organize and manage your API endpoints.

2024年6月29日 12:07 回复

你的答案