简体   繁体   English

Node.js 环境变量未定义

[英]Node.js environment variables undefined

I'm trying to use environment variables but when I use the file and run the server, I am getting only PORT variable and all of my other variables are undefined.我正在尝试使用环境变量,但是当我使用该文件并运行服务器时,我只得到了 PORT 变量,而我的所有其他变量都未定义。 I'm using nodemon.我正在使用 nodemon。

.env .env

PORT=3000
SENDGRID_API_KEY=sometext

package.json包.json

"scripts": {
    "start": "node src/index.js",
    "dev": "env-cmd -f ./config/dev.env nodemon src/index.js"
  }

index.js索引.js

const port = process.env.PORT
const apiKey = process.env.SENDGRID_API_KEY
app.listen(port, () => {  
    console.log('Server is up on port '+port)
    console.log(apiKey)
})

Try to use dotenv npm尝试使用dotenv npm


import * as dotenv from 'dotenv'

dotenv.config(); 
export class Constants { 

  process.env.<YOUR_VARIABLE_NAME>

}

If you use -f than it wont care about the environment -e, use one of these.如果您使用-f不是它不会关心环境 -e,请使用其中之一。

"env-cmd nodemon src/index.js"

.rc file ./.env-cmdrc

{
  "development": {
    "ENV1": "Thanks",
    "ENV2": "For All"
  },
  "test": {
    "ENV1": "No Thanks",
    "ENV3": "!"
  },
  "production": {
    "ENV1": "The Fish"
  }
}

// Command: // 命令:

env-cmd -e production nodemon index.js

Check: https://github.com/toddbluhm/env-cmd检查: https : //github.com/toddbluhm/env-cmd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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