3 回答

TA貢獻1821條經驗 獲得超6個贊
2021 年更新
NestJS 現在原生支持原始答案。
此外,當主要功能是對 API 進行版本控制時, NestJS v8還添加了更復雜的路由:
@Controller({
? path: 'cats',
? version: '1', // ??
})
export class CatsController {
...
原答案
在 NestJS 中實現這一點的最可靠的方法是使用Nest-router包來創建路由樹。
yarn add nest-router
# or npm i nest-router
main.ts在名為的旁邊創建一個文件,routes.ts如下所示:
import { Routes } from 'nest-router';
import { YourModule } from './your/your.module';
export const routes: Routes = [
? {
? ? path: '/v1',
? ? module: YourModule,
? },
];
然后,在文件中,在加載任何其他模塊之前app.module.ts添加路由器:
@Module({
? imports: [
? ? RouterModule.forRoutes(routes),
? ? YourModule,
? ? DebugModule
? ],
})
現在,當您導航到控制器時,在本例中YourModule,其所有路由都將以 例如 為前綴:v1
curl http://localhost:3000/v1/your/operation
使用這種方法可以為您提供最大的靈活性,因為每個模塊不需要知道它的前綴如何;應用程序可以在更高級別上做出決定。與依賴靜態字符串相比,幾乎更高級的前綴可以動態計算。

TA貢獻1898條經驗 獲得超8個贊
對我來說,僅僅為了實現這一點而添加第三方包有點不必要,更不用說它過時/不維護的風險了。您可以在類中添加自定義路由前綴Controller。
@Controller('custom/prefix')
export const MyController {
@Get('health')
getHealth() {
//this route would be: custom/prefix/health
return {};
}
@Get('other')
getOther() {
//this route would be: custom/prefix/other
return {};
}
}
然后只需將此控制器添加到您的Module

TA貢獻1900條經驗 獲得超5個贊
您現在可以使用 RouterModule 配置,也可以從全局前綴配置中排除某些路徑(或混合使用兩者):
路由器模塊: https://docs.nestjs.com/recipes/router-module#router-module
全局前綴“排除”: https ://docs.nestjs.com/faq/global-prefix#global-prefix
添加回答
舉報