我正在开发一个连接到第三方API的应用程序,这些API需要使用应用程序ID和密钥。
我将这些值作为环境变量存储在heroku中,这样我就不需要在代码中公开它们。
如果我部署到heroku,它将使用heroku的环境变量来解析这些API凭据。
如果我在本地使用它,我想使用我的config.js
模块,并在那里查找API凭据。注意:此config.js
文件包含在我的.gitignore
中,因此这些凭据永远不会出现在云中。
有问题的代码如下:
var api_secret = process.env.API_SECRET || require('../../config.js').secret;
当我在本地运行它时,我没有任何问题。这意味着它无法解析环境变量,因此它使用config.js
中的secret
。
当我在heroku上运行它时,它确实抛出了一个错误,告诉我module 'config.js' could not be found
。这是有道理的,因为它永远不会随着repo的其余部分一起被推高,因为它在我的.gitignore
中。
因为heroku在我的代码运行之前就会解析它,所以require('../../config.js')
是有问题的。它正在尝试查找一个不存在的文件。
如何解决部署时使用环境变量和本地运行时使用config.js
模块的问题?
发布于 2015-06-03 21:19:45
在您的应用程序的Heroku仪表板上,您可以设置配置变量。如果您的机器上设置了Heroku工具带,您还可以使用:
heroku config:set API_SECRET=secret
有关详细信息,请参阅this article。
编辑:我想我可能误解了这个问题。我建议,如果可能的话,使用dotenv npm package在本地设置配置变量。
如果不是,另一件需要检查的事情是config.js
包是否在您的package.json
文件中,因为Heroku将使用它来构建依赖项。
发布于 2015-06-03 23:52:22
如果你根本不想把你的config.js
推到heroky,你可以通过try catch和文件系统模块来确定配置文件是否存在:
Check synchronously if file/directory exists in Node.js
在您的案例中:
var fs = require('fs'),
api_secret,
config;
try {
// Check whether config.js exists
config = fs.lstatSync('../../config.js');
// If we reach this line then config.js exists, yay!
api_secret = process.env.API_SECRET || require('../../config.js').secret;
// or alternatively api_secret = require('../../config.js').secret;
// depending on your logic
}
catch (e) {
// else config.js does not exist
api_secret = process.env.API_SECRET
}
要以编程方式运行Heroku命令,您可以设置一个免费的Ruby应用程序,并通过API调用让它做您想做的事情。使用Heroku-api。请参阅https://github.com/heroku/heroku.rb
如果您想手动设置Heroku命令,您可以使用命令heroku config:set MYVAR=MYVALUE
或通过Heroku仪表板在Heroku上设置环境变量(单击您的应用程序>设置>显示配置变量>编辑)。
https://stackoverflow.com/questions/30630866
复制相似问题