【问题标题】:Why is dotenv returning port as undefined when referencing through dotenv?为什么在通过 dotenv 引用时 dotenv 返回端口未定义?
【发布时间】:2023-01-07 01:10:40
【问题描述】:

昨天,我安装并引用了 dotenv,服务器通过 env 在端口 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')
//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`);
});

当我使用直接通过 server.js 调用的端口号运行时,端口加载为 4000:

但是当我运行环境变量时,我得到了未定义的信息:

这并不重要,但我关闭了我的 VPN 并重新启动了它。不知道为什么现在会出错。

【问题讨论】:

  • .env 文件位于何处?
  • dotenv.config() 之前没有process.env.PORT

标签: javascript node.js reactjs


【解决方案1】:

在您的 server.js 文件中,您在调用 dotenv.config() 之前使用 process.env.PORT 定义了 PORT const,因为您尚未定义环境变量。

尝试将您的代码更改为:

dotenv.config({ path: 'backend/config/config.env'});

const PORT = process.env.PORT || 4000;

const URI = process.env.URI;

【讨论】:

  • 您甚至可以从 const dotenv = require ('dotenv') 中再删除一行并更新:require('dotenv').config({ path: 'backend/config/config.env'});全部在一行中。
【解决方案2】:

Alan 是正确的,const PORT 是在调用 dotenv.config() 之前定义的。

谢谢,Alan 和 Jeff,老实说我没看到。

我想从现在开始我会把这个序列放在一行中,就像水杨建议的那样。

【讨论】:

    猜你喜欢
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-23
    • 1970-01-01
    • 2019-12-04
    • 2020-10-14
    相关资源
    最近更新 更多