首页 > 解决方案 > Nest 的 ConfigService 无法拉取 .env 变量

问题描述

我想实现Nestjs v8.1.1的ConfigService

我已将 .env 文件放在项目的根目录(不是 src 文件夹)中,该文件包含以下内容:

HOST=http://localhost
PORT=8088

app.Module.ts 通过导入来丰富:

@Module({
  imports: [ 
    ConfigModule.forRoot({
      isGlobal: true,
      cache: true,
      envFilePath: '.env',
    }), 
   ...]

我已经尝试过不使用这些选项并使用这些列出的选项。

当它试图获取变量的值时,它会导致

var address = this.configService.get('HOST', 'http://localhost')
                                     ^
TypeError: Cannot read properties of undefined (reading 'get')

仅供参考,代码在扩展类中运行,这不应该有所作为。

export default class KsqldbSignalsClient extends ClientProxy {

  constructor(private configService: ConfigService) {
    super()
  }
    
  async connect(): Promise<any> {
    var address = this.configService.get('HOST', 'http://localhost')
    ...

任何提示(甚至确认它对您有用)都值得赞赏。

标签: nestjsnestjs-config

解决方案


用装饰KsqldbSignalsClient班级@Injectable()


推荐阅读