简体   繁体   English

如何在 node.js 中设置和使用环境变量

[英]how to set and consume environment variables in node.js

so I have a .env file in my TypeScript-node project.所以我的 TypeScript-node 项目中有一个 .env 文件。 It contains a session variable like this:它包含一个像这样的会话变量:

SESSION_SECRET= EXAMPLEkeyHERE1
 BIRD_STRIPE_KEY= TheseAreNotReAlKeYS
CIRC_STRIPE_KEY= XXXXXX1232abc

and Importing using :和导入使用:

import session = require('express-session'); const { SESSION_SECRET, PORT } = process.env;

and my app.js looks like this:我的 app.js 看起来像这样:

if (!SESSION_SECRET) {
logger.error('No client secret. Set SESSION_SECRET environment variable.');
process.exit(1);
}

 /**
 * @description Create Express server.
 */
 const app = express();

if (IS_DEVELOPMENT) {
   /**
    * @description Error Handler. Provides full stack - remove for production
    */
 app.use(errorHandler());
 }

 /**
  * @description Express configuration
  */
  app.set('port', PORT || 3000);
  app.use(
   cors(),
   compression(),
   express.json(),
   session({
    secret: SESSION_SECRET,
    resave: true,
    saveUninitialized: false
})
);

/**
 * @description Express routers
 */
const routers = {
     api: express.Router(),
     provider: express.Router()
 };

 routers.api.use([routers.provider]);
 routers.provider.use('/provider', [routes.Bird, routes.Circ, routes.Lime, routes.Spin, routes.Tier]);

/**
 * @description These line will add /api/v{version} route prefix in every api requests.
 */
 app.use(`/api/v${API_CONFIG.versions.v1}`, routers.api);

/**
 * @description These lines are including error404 exported module and it will get called when routes not found.
 */
  app.use([middleware.Error404]);

 /**
 * @var server
 * @description Start Express server.
 */
 app.listen(app.get('port'), () => {
     console.log('App is running at http://localhost:%d in %s mode', app.get('port'), app.get('env'));
      console.log('Press CTRL-C to stop\n');
   }); 

when I hit npm start I get this error:当我点击npm start我收到此错误:

> @ruler-mobility/ruler@1.0.0 serve /Users/macbook/Desktop/develop/rails-projects/ruler
> node src/app.js

 error: No client secret. Set SESSION_SECRET environment variable. {"service":"user-service"}
 npm ERR! code ELIFECYCLE
 npm ERR! errno 1
 npm ERR! @ruler-mobility/ruler@1.0.0 serve: `node src/app.js`
 npm ERR! Exit status 1

so you can see the error is logged from the first if statement in the code.所以你可以看到错误是从代码中的第一个 if 语句记录的。 It could also be failing under express configuration.它也可能在快速配置下失败。

I have tried setting the SESSION_SECRET as a string SESSION_SECRET= "EXAMPLEkeyHERE1" in my .env file but it made no difference.我已经尝试设置SESSION_SECRET作为字符串SESSION_SECRET= "EXAMPLEkeyHERE1"在我.ENV文件,但它并没有区别。 can anyone tell me what I'm doing wrong here?谁能告诉我我在这里做错了什么?

You can use dotenv to load up env variables:您可以使用dotenv加载环境变量:

npm install dotenv -D

and then as soon as possible in your script:然后尽快在您的脚本中:

require('dotenv').config()

It is not clear to me if your problem is reading a configuration file or accessing environment variables.我不清楚您的问题是读取配置文件还是访问环境变量。

In order to access environment variables, you just have to use process.env.VARNAME .为了访问环境变量,您只需要使用process.env.VARNAME This supposes that the environment variable is properly set, eg这假设环境变量已正确设置,例如

> SESSION_SECRET="EXAMPLEkeyHERE1" node src/app.js

But if you want to put your configuration in a file, you can either use a .json file which you require or use a library managing configuration, like confinode , which will search, load and parse the file for you.但是,如果你想要把你的配置文件,您可以使用一个.json您的文件require或使用库管理的配置,像confinode ,这将搜索,加载和分析文件给你。

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

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