简体   繁体   English

如何从节点中的 express 访问.env 变量?

[英]How to access .env variables from express in node?

I try to return my env variables in an express file but I get null .我尝试在快速文件中返回我的环境变量,但我得到null

This is my folder structure这是我的文件夹结构

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

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

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

Usage As early as possible in your application, require and configure 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

so in your case所以在你的情况下

/src/ 
   index.ts
   .env

You can also check for errors您还可以检查错误

const result = dotenv.config()

if (result.error) {
  throw result.error
}

console.log(result.parsed)
  • In the .env , it should be:.env中,它应该是:
TEST=mytest
  • (If the modification above doesn't work) Since the .env is not in the same folder as index.ts file, you may need to provide the path to the .env file. (如果上面的修改不起作用)由于.envindex.ts文件不在同一个文件夹中,您可能需要提供.env文件的路径。

At the beginning of your index.ts file:index.ts文件的开头:

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

Fixed this by doing two things:通过做两件事来解决这个问题:

Firstly created .env file by using the terminal.首先使用终端创建.env文件。 ( see reference ) 见参考

Then, I moved .env file to the root folder of my backend (removing it from src )然后,我将.env文件移动到后端的root文件夹(从src中删除)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM