3 回答

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超6個(gè)贊
2021 年更新
NestJS 現(xiàn)在原生支持原始答案。
此外,當(dāng)主要功能是對 API 進(jìn)行版本控制時(shí), NestJS v8還添加了更復(fù)雜的路由:
@Controller({
? path: 'cats',
? version: '1', // ??
})
export class CatsController {
...
原答案
在 NestJS 中實(shí)現(xiàn)這一點(diǎn)的最可靠的方法是使用Nest-router包來創(chuàng)建路由樹。
yarn add nest-router
# or npm i nest-router
main.ts在名為的旁邊創(chuàng)建一個(gè)文件,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
? ],
})
現(xiàn)在,當(dāng)您導(dǎo)航到控制器時(shí),在本例中YourModule,其所有路由都將以 例如 為前綴:v1
curl http://localhost:3000/v1/your/operation
使用這種方法可以為您提供最大的靈活性,因?yàn)槊總€(gè)模塊不需要知道它的前綴如何;應(yīng)用程序可以在更高級別上做出決定。與依賴靜態(tài)字符串相比,幾乎更高級的前綴可以動態(tài)計(jì)算。

TA貢獻(xiàn)1898條經(jīng)驗(yàn) 獲得超8個(gè)贊
對我來說,僅僅為了實(shí)現(xiàn)這一點(diǎn)而添加第三方包有點(diǎn)不必要,更不用說它過時(shí)/不維護(hù)的風(fēng)險(xiǎn)了。您可以在類中添加自定義路由前綴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貢獻(xiàn)1900條經(jīng)驗(yàn) 獲得超5個(gè)贊
您現(xiàn)在可以使用 RouterModule 配置,也可以從全局前綴配置中排除某些路徑(或混合使用兩者):
路由器模塊: https://docs.nestjs.com/recipes/router-module#router-module
全局前綴“排除”: https ://docs.nestjs.com/faq/global-prefix#global-prefix
添加回答
舉報(bào)