简体   繁体   中英

How to access .env variables from express in node?

I try to return my env variables in an express file but I get null .

This is my folder structure

--backend
  --.env
  --src
    --index.ts

--frontend
//.env
TEST: mytest
//index.ts
app.get("/api/test", (request, response) => {
  response.send({test: [process.env.TEST]})
})

Install https://www.npmjs.com/package/dotenv

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

require('dotenv').config()


// server.js
console.log(`Your port is ${process.env.PORT}`); // undefined
const dotenv = require('dotenv');
dotenv.config();
console.log(`Your port is ${process.env.PORT}`); // 8626

so in your case

/src/ 
   index.ts
   .env

You can also check for errors

const result = dotenv.config()

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

console.log(result.parsed)
  • In the .env , it should be:
TEST=mytest
  • (If the modification above doesn't work) Since the .env is not in the same folder as index.ts file, you may need to provide the path to the .env file.

At the beginning of your index.ts file:

require('dotenv').config({path : path.resolve(__dirname, '../.env')});

Fixed this by doing two things:

Firstly created .env file by using the terminal. ( see reference )

Then, I moved .env file to the root folder of my backend (removing it from src )

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