在控制器上嵌套.js访问process.env



如何访问nest.js中的process.env.SOME_FIELD?

应用程序模块.ts

...
modules: [
...
ConfigModule.forRoot({
envFilePath: '.env.' + process.env.APP_CODE
}),
CatModule
...
]
...

CatModule 中的CatController.ts

// Below line is not working
console.log(process.env.APP_CODE) // process.env.APP_CODE is undefined
export class CatController {
constructor() {
console.log(process.env.APP_CODE) // This is working
}
}

在类定义之前,我需要在CatController.ts访问process.env.APP_CODE,但是,这是未定义的

我该怎么解决这个问题?

设置envFilePath。env文件路径因此,您应该在文件中定义env变量在控制器中,你可以得到这样的

export class CatController {
constructor(configService: ConfigService) {}

get() {
return this.configService.get<string>('APP_CODE')
}
}

更详细的使用,你可以看到文档

在你的app.module.ts导入上试试这个

ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env.' + process.env.APP_CODE
}),

通过使用ConfigModule,您将对config的调用从dotenv委派给异步调用的ConfigService。因此,无法保证在导入CatsController时会调用config,因此process.env检索将返回基本对象,而不是来自.env文件的额外配置值。要解决此问题,您可以添加

import { config } from 'dotenv';
config()

作为main.ts的前两行,它应该可以解决您的问题。

最新更新