[英]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)
.env
, it should be:.env
中,它应该是:TEST=mytest
.env
is not in the same folder as index.ts
file, you may need to provide the path to the .env
file. .env
与index.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.