简体   繁体   English

如何在 Express 的本地主机上设置 process.env 变量?

[英]How can one set process.env variables on their localhost in Express?

I want my code to run for both testing on my localhost, as well as my server.我希望我的代码在本地主机和服务器上运行以进行测试。

In heroku there is a GUI to do this, but how do I set these locally?在 heroku 中有一个 GUI 可以执行此操作,但我如何在本地设置这些?

There are a few ways to set an environment variable before running a program. 在运行程序之前,有几种方法可以设置环境变量。

You can do it at the same time as you start it: 您可以在启动的同时进行操作:

ENV=test ./start-server

Or in the same shell session: 或在同一shell会话中:

export ENV=test
./start-server

My preferred solution is to use the npm package called dotenv. 我的首选解决方案是使用名为dotenv的npm软件包。 If you require it in the entry point to your app it will read in any values in your .env file and make them available to your Node / Express application via process.env. 如果您在应用程序的入口点中需要它,它将读取.env文件中的所有值,并通过process.env将其提供给Node / Express应用程序。 Now you can simply create the necessary.env files in your various environments. 现在,您可以在各种环境中简单地创建必要的.env文件。 You don't need to deal with passing a bunch of arguments to npm scripts. 您无需处理将大量参数传递给npm脚本的问题。 Of course, if you have passwords or API keys in your .env file be sure to add .env to your .gitignore file #captainobvious 当然,如果您的.env文件中包含密码或API密钥,请确保将.env添加到您的.gitignore文件中#captainobvious

If you use nodemon on local (why wouldn't anyone use nodemon?) you can drop a file in the root of your project called nodemon.json.如果您在本地使用 nodemon(为什么没有人使用 nodemon?),您可以在项目的根目录下放置一个名为 nodemon.json 的文件。 It will make the variables in the file available to your process env vars.它将使文件中的变量可用于您的进程环境变量。

nodemon.json nodemon.json

{
  "env": {
    "MSSQL_DATABASE": "MySqlDb",
    "MSSQL_USER": "MySqlUser",
    "MSSQL_PASSWORD": "MySqlPassword"
  }
}

app.js应用程序.js

const database = process.env.MSSQL_DATABASE;
const username = process.env.MSSQL_USER;
const password = process.env.MSSQL_PASSWORD;

Of course you should add nodemon.json to your.gitignore file, especially if it contains sensitive information.当然,您应该将 nodemon.json 添加到您的 .gitignore 文件中,尤其是当它包含敏感信息时。

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

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