Problem:
The server cannot detect process.env.PORT
from my .env file, saying PORT=5000
, and I have dotenv installed. process.env.port
returns undefined
Is something wrong?
I have a very basic express server that runs fine:
const express = require('express');
const path = require('path');
const dotenv = require('dotenv')
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)
On server start:
Server started at http://localhost:8080
process.env.PORT = undefined
console.log(process.env.PORT)
on the bottom of express script returned undefined
I have dotenv installed, proof:
$ npm ls dotenv
eloquent-javascript@ /Users/dana/code/eloquent-javascript
└── [email protected]
My .env file has the following content:
PORT=5000
What is wrong with my setup?
I have express.js, .env and installed dotenv
via npm.
Question: Why couldn’t express.js
grab my variable via process.env.PORT
from the .env
file?
2
Answers
you need yo configure dotenv.
https://www.npmjs.com/package/dotenv
Try to replace this:
with this: