【问题标题】:Why my static class cannot read the enviroment variable?为什么我的静态类不能读取环境变量?
【发布时间】:2022-11-30 16:17:58
【问题描述】:

我正在使用 ES6 标准构建一个 node.js 程序。

这是我的 package.json:

{
  "name": "react18es6",
  "version": "0.1.0",
  "private": true,
  "type": "module",
  "dependencies": {
    "@testing-library/jest-dom": "^5.16.4",
    "@testing-library/react": "^13.2.0",
    "@testing-library/user-event": "^13.5.0",
    "activedirectory": "^0.7.2",
    "bootstrap": "^5.1.3",
    "cross-env": "^7.0.3",
    "dotenv": "^16.0.3",
    "express": "^4.18.1",
    "mysql2": "^2.3.3",
    "nodemon": "^2.0.20",
    "npm-run-all": "^4.1.5",
    "react": "^18.1.0",
    "react-bootstrap": "2.2.1",
    "react-dom": "^18.1.0",
    "react-scripts": "^5.0.1",
    "web-vitals": "^2.1.4"
  },
  "scripts": {
    "build": "react-scripts build",
    "dev": "cross-env NODE_ENV=development run-p server start",
    "eject": "react-scripts eject",
    "prod": "cross-env NODE_ENV=production npm run server",    
    "server": "nodemon -r dotenv/config ./server/index.js",
    "start": "react-scripts start",
    "testServer":"cross-env NODE_ENV=development node -r dotenv/config ./server/index.js",
    "test": "react-scripts test"
  },
  "eslintConfig": {
    "extends": [
      "react-app",
      "react-app/jest"
    ]
  },
  "browserslist": {
    "production": [
      ">0.2%",
      "not dead",
      "not op_mini all"
    ],
    "development": [
      "last 1 chrome version",
      "last 1 firefox version",
      "last 1 safari version"
    ]
  }
}

我的 .env.development:

DATABASE_CHARSET=utf8

我的配置.js:

export class dbConfig{
    static charset =process.env["DATABASE_CHARSET"];
}

我的索引.js:

import dotenv from 'dotenv';
import {dbConfig} from './config.js';

dotenv.config({ path: '.env.'+process.env.NODE_ENV });
console.log(dbConfig);
console.log(process.env["DATABASE_CHARSET"])

我正在使用以下命令来执行代码:

npm run testServer

index.js 的输出如下:

[class dbConfig] {
  charset: undefined      
}
utf8

为什么dbConfig.js获取不到环境变量?

我试过suggested solution,但不幸的是,它不起作用。

【问题讨论】:

    标签: javascript node.js environment-variables


    【解决方案1】:

    您需要将其添加到您的My config.js 文件之上,以便它可以从process.env 读取

    import dotenv from 'dotenv';

    【讨论】:

      猜你喜欢
      • 2013-02-06
      • 1970-01-01
      • 2015-09-03
      • 1970-01-01
      • 2013-03-24
      • 1970-01-01
      • 1970-01-01
      • 2020-01-08
      • 2011-12-08
      相关资源
      最近更新 更多