简体   繁体   English

heroku 环境变量返回未定义

[英]heroku environment variables return undefined

I tried to set some env.我试图设置一些环境。 variables on Heroku and I did, I can see the variables in the app when opening the Heroku dashboard. Heroku 上的变量,我做到了,我可以在打开 Heroku 仪表板时看到应用程序中的变量。 But When I try to access the variables from my app it return undefined any idea?但是当我尝试从我的应用程序访问变量时,它返回undefined任何想法?

componentDidMount() {
    console.log('this env' , process.env.backEndServer) // undefined
}

checking in the Heroku cli:检查 Heroku cli:

$ heroku config:get backEndServer // https://myserver.com

You're trying to access the environment variable on client side and this is not possible.您正在尝试访问客户端的环境变量,这是不可能的。

If you want to use environment variables on your client side application you need to set up Webpack to handle different environments.如果要在客户端应用程序中使用环境变量,则需要设置 Webpack 来处理不同的环境。

In Webpack config files, you'll define your global variables for each environment using Webpack's Define plugin .在 Webpack 配置文件中,您将使用Webpack 的定义插件为每个环境定义全局变量。

Also don't forget to add NODE_ENV config variable to your heroku app and set it to true. So you'll be sure that by accessing另外不要忘记将NODE_ENV配置变量添加到您的 heroku 应用程序并将其设置为true. So you'll be sure that by accessing true. So you'll be sure that by accessing process.ENV.NODE_ENV will force runtime to use node.js` environment. true. So you'll be sure that by accessing process.ENV.NODE_ENV will force runtime to use node.js` 环境。

Now you can configure you're production environment as following:现在您可以按如下方式配置您的生产环境:

/* in webpack.config-prod.js */
...,
plugins: [    
  new webpack.DefinePlugin({           
    NODE_ENV: JSON.stringify(process.env.NODE_ENV),      
    API_HOST: JSON.stringify(process.env.API_HOST)
  })
],
...

Now you can easily access you're environment variables in your client side app.现在,您可以在客户端应用程序中轻松访问您的环境变量。

If you check the Heroku build log, it recommends that you specify a nodejs version.如果您查看 Heroku 构建日志,它建议您指定 nodejs 版本。 If you specify a node version in your package.json, it might fix the problem.如果您在 package.json 中指定节点版本,它可能会解决问题。

package.json包.json

{
...
  "engines": {
   "node": "12.13.1"
   },
...
}

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

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