skip to Main Content

I am having issue with the last 10 lines of code where I am working with a .env. I have already added my .env file with the MESSAGE_STYLE=uppercase.

However, when starting the local server with npm start, i get the lower case version of my "hello json" message, not the upper case version.

It also says my secret.env file in root is there and says A now, isntead of U, as undefined, idk what I did differently, however, I am still getting my output as :
{
"message": "Hello json"
}

not what i am expecting to be:

{
"message": "Hello json"
}

Input:

let express = require('express');
let app = express();
require('dotenv').config();



app.use("/public", express.static(__dirname + "/public"))


app.get("/", (req, res) => {
    res.sendFile (__dirname + "/views/index.html");

})

app.get ("/json", (req, res) => {
    if ( process.env["MESSAGE_STYLE"] == "uppercase"){
        res.json({"mesage": "HELLO JSON"});
    } else {
         res.json({"message": "Hello json"});
    }
})

module.exports = app;


2

Answers


  1. Can you change the order of the import?

    So instead of having

    let express = require('express');
    let app = express();
    require('dotenv').config();
    

    You have to do

    require('dotenv').config(); // Make sure this is on the first line of your file
    let express = require('express');
    let app = express();
    

    If it’s not helping you can also use the debug mode for dotenv

    require('dotenv').config({ debug: true });
    

    Or you can also debug using:

    console.log(require('dotenv').config())
    
    Login or Signup to reply.
  2. According to the dotenv documentation, the environment variables are loaded from the .env file by default. If you want to load them from a custom secret.env file, you need to configure it:

    require('dotenv').config({ path: 'secret.env' })
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search