为何Express.js无法通过dotenv读取.env文件中的process.env.PORT变量?
问题原因及解决办法
你代码里只引入了dotenv,但没执行它的config()方法,导致.env文件里的变量根本没被加载到process.env中,自然读不到PORT值。
具体解决步骤:
- 执行dotenv.config():必须在读取
process.env之前调用该方法,把它放在定义port变量的代码前面。修改后的完整代码如下:
const express = require('express'); const path = require('path'); const dotenv = require('dotenv') // 关键:先加载.env文件 dotenv.config(); const app = express(); const port = process.env.PORT || 8080; // sendFile will go here app.get('/', function(req, res) { res.sendFile(path.join(__dirname, '/index.html')); }); app.listen(port); console.log('Server started at http://localhost:' + port); console.log(process.env.PORT)
- 确认.env文件位置:确保.env文件和你的Express入口文件(比如server.js、app.js)在同一目录下。如果文件不在当前目录,需要在config方法里指定路径:
dotenv.config({ path: './your-folder/.env' });
- 检查.env格式:变量定义不要加多余空格或引号,
PORT=5000是正确写法,避免写成PORT = 5000或PORT="5000"(引号虽能识别,但易引发格式问题)。
修改后重启服务器,就能正常读取到PORT=5000,控制台会输出Server started at http://localhost:5000和5000。
内容的提问来源于stack exchange,提问作者dmxt
相关产品推荐
相关产品推荐

