简体   繁体   中英

Environment variable undefined error in node.js

server.js


const express = require('express');

const dotenv = require('dotenv');


const error = require('./middleware/errorMiddlewareHandler');

const usersRoute = require('./routes/userRoute');

dotenv.config();

require('./config/dbConnect')();


const app = express();

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


//passing body data
app.use(express.json());

//user routes

//routes
app.use('/api/users', usersRoute);
console.log(process.env.JWT_KEY);




//error middleware
app.use(error.errorMiddlewareHandler);

app.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

whenever I run the code terminal is showing like

undefined

Server is listening on port 3000

I have already assigned the JWT_KEY correctly

JWT_KEY=stackoverflow

So any body knows the problem just let me know

You could check the result of config() (make sure the .env -file is in the root-dir in that case) via:

require('dotenv').config()

const result = dotenv.config()

if (result.error) {
  throw result.error
}

console.log(result.parsed)

and see if it configures correctly. -> see more infos on dotenv

I personally prefer to use a env_config.js file processing my envs and require it whenever needed (iE in app.js ).

env_config.js:

var path = require('path');


const dotenvAbsolutePath = path.join(__dirname, '.env');

/* INFO: Require dotenv package for retieving and setting env-vars at runtime via absoliute path due to pkg */

  const dotenv = require('dotenv').config({
    path: dotenvAbsolutePath
  });
  if (dotenv.error) {
    console.log(`ERROR WHILE READING ENV-VARS:${dotenv.error}`);
    throw dotenv.error;
  }

module.exports = {
  nodeEnv: process.env.NODE_ENV,
  nodePort: process.env.NODE_PORT,
  deviceLocation: process.env.DEVICE_LOCATION,
  hostWLC: process.env.HOST_WLC,
  hostPostgresql: process.env.HOST_POSTGRESQL,
  portPostgresql: process.env.PORT_POSTGRESQL,
  dbPostgresql: process.env.DB_POSTGRESQL,
  userPostgresql: process.env.USER_POSTGRESQL,
  pwdPostgresql: process.env.PWD_POSTGRESQL,
  hostMQTT: process.env.HOST_MQTT,
  portMQTT: process.env.PORT_MQTT,
  userMQTT: process.env.USER_MQTT,
  pwdMQTT: process.env.PWD_MQTT,
};

app.js:

const { nodePort } = require('./env-config');
....
...
..
app.listen(nodePort, () => console.log(`Node's Express someApp is listening on Port ${nodePort}..`));

.env file (in root dir):

NODE_ENV=******
NODE_PORT=******
DEVICE_LOCATION=******
HOST_WLC=******
HOST_POSTGRESQL=******
PORT_POSTGRESQL=******
DB_POSTGRESQL=******
USER_POSTGRESQL=******
PWD_POSTGRESQL=******
HOST_MQTT=******
PORT_MQTT=******
USER_MQTT=******
PWD_MQTT=******

Normal usage according to official docs:

As early as possible in your application, require and configure dotenv.

require('dotenv').config()

Create a.env file in the root directory of your project. Add environment-specific variables on new lines in the form of NAME=VALUE. For example:

DB_HOST=localhost
DB_USER=root
DB_PASS=s1mpl3

process.env now has the keys and values you defined in your.env file.

const db = require('db')
db.connect({
  host: process.env.DB_HOST,
  username: process.env.DB_USER,
  password: process.env.DB_PASS
})

At the top of the file require and configure dotenv require("dotenv").config() Delete the other configs you have already

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM