【问题标题】:dotenv is undefined in expressdotenv 在 express 中未定义
【发布时间】:2020-11-14 21:23:56
【问题描述】:

我的根目录中有一个.env 文件,里面有PORT=4000

我的app.js 有以下代码

const express = require('express');
const app = express();
const port = process.env.PORT || 3000;

require('dotenv').config();

app.get('/', (req, res) => {
  res.send('Hello World!!!');
  console.log(port);
});

app.listen(port, () => console.log(`Example app listening on port ${port}!`));

但是当我使用nodemon app.js 运行应用程序时,port 是 3000 而不是 4000。为什么我的 .env PORT 变量未定义?

【问题讨论】:

  • require('dotenv').config(); 把它放在你的 js 文件的第一行

标签: node.js express dotenv


【解决方案1】:

在端口变量之前不需要 env。所以你得到的是 3000 而不是 4000。只需使用此代码。它会正常工作的。

    const express = require('express');
    const app = express();
    require('dotenv').config();
    const port = process.env.PORT || 3000;
    
    app.get('/', (req, res) => {
      res.send('Hello World!!!');
      console.log(port);
    });
    
    app.listen(port, () => console.log(`Example app listening on port ${port}!`));

【讨论】:

  • 您在端口变量之前不需要 env。所以你得到 3000 而不是 4000
  • 这样做会给我以下错误:错误:监听 EADDRINUSE:地址已在使用 4000;
  • 一些进程已经在使用 4000 端口。找出 pid 然后终止该进程。然后再次运行你的项目
  • 我刚刚删除了我的项目并尝试了您的版本并且它有效。猜猜我删除的文件夹发生了什么奇怪的事情:/
【解决方案2】:

这段代码解决了问题

require('dotenv').config();

const express = require('express');
const app = express();
const port = process.env.PORT;

app.get('/', (req, res) => {
  res.send('Hello World!!!');
});

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`);
});

【讨论】:

    猜你喜欢
    • 2020-08-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-07
    • 1970-01-01
    • 2020-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多