【问题标题】:How to access .env variables from express in node?如何从 node 中的 express 访问 .env 变量?
【发布时间】:2021-06-07 21:23:02
【问题描述】:

我尝试在一个 express 文件中返回我的环境变量,但我得到了null

这是我的文件夹结构

--backend
  --.env
  --src
    --index.ts

--frontend
//.env
TEST: mytest
//index.ts
app.get("/api/test", (request, response) => {
  response.send({test: [process.env.TEST]})
})

【问题讨论】:

    标签: node.js express environment-variables


    【解决方案1】:

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

    用法 尽早在您的应用程序中要求并配置 dotenv。

    require('dotenv').config()

    
    // server.js
    console.log(`Your port is ${process.env.PORT}`); // undefined
    const dotenv = require('dotenv');
    dotenv.config();
    console.log(`Your port is ${process.env.PORT}`); // 8626
    

    在你的情况下

    /src/ 
       index.ts
       .env
    

    您还可以检查错误

    const result = dotenv.config()
    
    if (result.error) {
      throw result.error
    }
    
    console.log(result.parsed)
    

    【讨论】:

    • 仍未定义。也许 .env 文件在错误的地方?对不起,我不知道
    • 移动.env到src里面,它会自动加载
    【解决方案2】:
    • .env中,应该是:
    TEST=mytest
    
    • (如果上面的修改不起作用)由于.envindex.ts文件不在同一个文件夹中,您可能需要提供.env文件的路径。

    index.ts 文件的开头:

    require('dotenv').config({path : path.resolve(__dirname, '../.env')});
    

    【讨论】:

      【解决方案3】:

      通过做两件事来解决这个问题:

      首先使用终端创建.env文件。 (see reference)

      然后,我将.env 文件移动到后端的root 文件夹(从src 中删除)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-12-03
        • 1970-01-01
        • 1970-01-01
        • 2016-06-11
        • 2022-08-24
        • 2021-08-07
        • 2021-01-03
        相关资源
        最近更新 更多