Javascript 控制器上的Nest.js access process.env
如何访问nest.js中的process.env.SOME_字段 应用程序模块.tsJavascript 控制器上的Nest.js access process.env,javascript,node.js,environment-variables,nestjs,Javascript,Node.js,Environment Variables,Nestjs,如何访问nest.js中的process.env.SOME_字段 应用程序模块.ts ... modules: [ ... ConfigModule.forRoot({ envFilePath: '.env.' + process.env.APP_CODE }), CatModule ... ] ... CatModule中的CatController.ts // Below line is not working con
...
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\u code
,但是,这是未定义的
如何解决此问题?envFilePath已设置。env file path 因此,您应该在文件中定义env变量 在控制器中,你可以这样得到它
export class CatController {
constructor(configService: ConfigService) {}
get() {
return this.configService.get<string>('APP_CODE')
}
}
导出类CatController{
构造函数(configService:configService){}
得到(){
返回此.configService.get('APP\u CODE')
}
}
更详细的用法,您可以查看在您的app.module.ts导入中尝试此功能
ConfigModule.forRoot({
isGlobal: true,
envFilePath: '.env.' + process.env.APP_CODE
}),
通过使用
ConfigModule
可以将对config
的调用从dotenv
委托给异步调用的ConfigService
。因此,无法保证在导入CatsController
时会调用config
,因此进程.env
检索将返回基本对象,而不是来自.env
文件的额外配置值。要解决此问题,您可以添加
import { config } from 'dotenv';
config()
作为
main.ts的前两行,它应该可以解决您的问题。但是,我不能在上课前访问get()
方法definition@MERN您应该从@nestjs/config导入ConfigService,然后可以使用ConfigService whitget()
@MERN我建议你仔细阅读文档,然后才能正确使用它