【问题标题】:ConfigService of nest cannot pull .env variableNest 的 ConfigService 无法拉取 .env 变量
【发布时间】:2021-12-07 21:04:49
【问题描述】:

我想实现 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')
    ...

感谢任何提示(甚至确认它对您有用)。

【问题讨论】:

  • 这意味着ConfigService 还没有被实例化。你用@Injectable()装饰了KsqldbSignalsClient类吗?
  • @msrumon 就是这样。谢谢
  • @msrumon,请将其作为答案发布,以便我标记给其他人。

标签: nestjs nestjs-config


【解决方案1】:

@Injectable() 装饰KsqldbSignalsClient 类。

【讨论】:

    【解决方案2】:

    第 1 步: 安装下面的2个包

    https://www.npmjs.com/package/config

    https://www.npmjs.com/package/dotenv

    第 2 步:

    @Module({
      imports: [ 
        ConfigModule.forRoot({
          host: process.env.HOST,
          port: process.env.PORT,
          envFilePath: '.env',
        }), 
       ...]
    

    第 3 步:

    然后在你的 KsqldbSignalsClient 类或任何地方 只需获取类似的值,

    var address = process.env.HOST;
    

    【讨论】:

    • 配置服务的思想是通过配置服务而不是直接访问所有环境变量。
    猜你喜欢
    • 1970-01-01
    • 2022-01-02
    • 2021-04-09
    • 2019-02-12
    • 2021-08-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    相关资源
    最近更新 更多