英文:
Why is dotenv returning port as undefined when referencing through dotenv?
问题
昨天,我已经安装并引用了dotenv,服务器通过环境变量调用端口4000,我已经使Postman工作并引用了服务器,但当我今天开始编码时停止了,我不知道我改了什么,因为我认为我什么都没做。
我的.env文件如下:
PORT = 4000
NODE_ENV = DEVELOPMENT
DB_URI = mongodb+srv://<xxx>:<xxx>@products.<xxx>.mongodb.net/?retryWrites=true&w=majority`
我的server.js
文件如下:
const app = require('./app');
const connectDatabase = require('./config/database');
const dotenv = require('dotenv');
// 我在这两个PORT常量之间切换以进行调试
const PORT = process.env.PORT
const PORT = 4000
const URI = process.env.URI
// 设置环境变量(教程通过根目录运行服务器,因此使用了backend/...路径)。
dotenv.config({ path: 'backend/config/config.env'});
// 数据库连接
connectDatabase();
app.listen(PORT, () => {
console.log(`服务器运行在端口: ${PORT},作为一个 ${process.env.NODE_ENV} 项目`);
});
当我直接通过server.js调用端口号运行时,端口加载为4000:
但当我通过环境变量运行时,我得到undefined:
虽然这并不重要,但我关闭了VPN并重新启动了它。不知道为什么现在会出现错误。
英文:
Yesterday, I had dotenv installed and referenced, and the Server was calling on port 4000 through env, I had Postman working and referencing the server but that stopped when I started my coding today, I have no idea what I changed, because I didn't think I had done anything.
My .env file is below:
PORT = 4000
NODE_ENV = DEVELOPMENT
DB_URI = mongodb+srv://<xxx>:<xxx>@products.<xxx>.mongodb.net/?retryWrites=true&w=majority`
My server.js
file is below:
const app = require ('./app');
const connectDatabase = require('./config/database');
const dotenv = require ('dotenv')
//I'm switching between these two PORT constants to debug
const PORT = process.env.PORT
const PORT = 4000
const URI = process.env.URI
// environment variable setup (tutorial runs server through the root, hence the backend/...).
dotenv.config({ path: 'backend/config/config.env'});
// DB connection
connectDatabase();
app.listen(PORT, () => {
console.log(`Server running on PORT: ${PORT} as a ${process.env.NODE_ENV} project`);
});
When I run with the port number called directly through server.js the port loads as 4000:
But when I run through the environment variables I get undefined:
Not that it matters, but I turned off my VPN and restarted it. Not sure why it makes the error now.
答案1
得分: 1
在你的 server.js 文件中,你正在使用 process.env.PORT 来定义 PORT 常量,在调用 dotenv.config() 之前,因此你的环境变量尚未被定义。
尝试将你的代码更改为:
dotenv.config({ path: 'backend/config/config.env' });
const PORT = process.env.PORT || 4000;
const URI = process.env.URI;
英文:
On your server.js file, you are defining the PORT const using the process.env.PORT before calling dotenv.config(), because of that you env vars are not defined yet.
Try change your code to:
dotenv.config({ path: 'backend/config/config.env'});
const PORT = process.env.PORT || 4000;
const URI = process.env.URI;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论