【问题标题】:Unable to set config file in nestjs application无法在 nestjs 应用程序中设置配置文件
【发布时间】:2021-02-05 22:44:25
【问题描述】:

我已经在我的 src 文件夹之外的 config 文件夹中创建了我的 .env 文件,我正在尝试将它加载到我的 main.ts 文件中。它总是给我 undefined 或 NAN。

我哪里错了?

GitHub 仓库:https://github.com/richakhetan/task-manager-nest

【问题讨论】:

    标签: javascript node.js express nestjs


    【解决方案1】:

    安装 dotenv npm i dotenv 并更新 main.ts 文件:

    import { ValidationPipe } from '@nestjs/common';
    import { NestFactory } from '@nestjs/core';
    import { AppModule } from './app.module';
    import * as dotenv from 'dotenv';
    import * as path from 'path';
    
    async function bootstrap() {
      dotenv.config({ path: path.resolve(__dirname, '../config/dev.env') });
      const app = await NestFactory.create(AppModule);
      console.log(process.env.PORT);
      app.useGlobalPipes(new ValidationPipe());
      await app.listen(3000);
    }
    
    bootstrap();

    【讨论】:

    • 不工作... (node:18404) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'resolve' of undefined at bootstrap (C:\Courses\Node JS\Project\task-manager-nest\dist \main.js:9:42) 在 Object. (C:\Courses\Node JS\Project\task-manager-nest\dist\main.js:15:1) 在 Module._compile (internal/modules /cjs/loader.js:1138:30) 在 Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10) 在 Module.load (internal/modules/cjs/loader.js: 986:32) 在 Function.Module._load (internal/modules/cjs/loader.js:879:14)
    • 你必须导入'path'模块
    • const config = dotenv.parse(fs.readFileSync("C:/Courses/Node JS/Project/task-manager-nest/src/config/dev.env"));这对我有用,但使用 read FileSync 是一个好习惯
    【解决方案2】:

    看起来您从未将 .env 文件加载到您的 process.env 中,dotenv 包使用 config() 方法执行此操作,但您需要提供它的路径,因为您不需要'根目录中没有.env,或命名为.env。您正在使用的 config 包似乎不支持 .env 文件格式,因此您应该使用类似 .jsonanything else supported by config 的东西

    【讨论】:

      【解决方案3】:

      我已经删除了 src 文件夹之外的 env 文件并创建了配置模块和服务。

      ConfigService.ts

      import { Injectable } from '@nestjs/common';
      
      import * as path from 'path';
      import * as dotenv from 'dotenv';
      import * as fs from 'fs';
      
      @Injectable()
      export class ConfigService {
          static constants(){
              const baseDir = path.join(__dirname, '../../dev.env');
              const config = dotenv.parse(fs.readFileSync(baseDir));
              return {
                  port: config.PORT,
                  mongoConnectionString: config.MONGODB_CONNECT,
                  jwtSecret: config.SECRETKEY,
                  sessionTime: config.SESSIONTIME
              }
          }
      
      }
      

      ConfigModule.ts

      import { Global, Module } from '@nestjs/common';
      import { ConfigService } from './config.service';
      
      @Global()
      @Module({
        providers: [ConfigService],
        exports: [ConfigService]
      })
      export class ConfigModule {
      }
      
      

      为了使用下面的代码使用值

      ConfigService.constants().port
      

      存储库中提供的详细代码

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-07-10
        • 2018-05-29
        • 2020-09-22
        • 2013-04-06
        • 1970-01-01
        • 2014-09-03
        • 2020-11-21
        • 1970-01-01
        相关资源
        最近更新 更多