简体   繁体   English

使用Rails在Heroku中隐藏Google API密钥

[英]Hiding Google API Key in Heroku using Rails

I am a newbie in Heroku. 我是Heroku的新手。 How do you hide your API key in the Heroku? 您如何在Heroku中隐藏您的API密钥? I know from the documentation I can use config vars 我从文档中知道我可以使用config vars

https://devcenter.heroku.com/articles/config-vars

But how do I load the config from JavaScript? 但是,如何从JavaScript加载配置? What I want to do is something like this 我想做的是这样的

https://developers.google.com/maps/documentation/javascript/tutorial

I'm using Ruby on Rails for my application. 我正在为我的应用程序使用Ruby on Rails。

A great way to use API keys without committing them into your code is to use environment variables. 使用API​​密钥而不将其提交到代码中的一种好方法是使用环境变量。 These are variables set in the shell of the system you're using to serve your Rails app that can be referenced in the code. 这些是在用于服务Rails应用程序的系统外壳中设置的变量,可以在代码中引用这些变量。 On Heroku, you will set an environment variable differently than on a standard Linux server. 在Heroku上,您将设置环境变量的方式与在标准Linux服务器上不同。

First, in your Rails app, you would insert the value of an environment variable like this: ENV["MY_API_KEY"] 首先,在Rails应用中,您将插入一个环境变量的值,如下所示: ENV["MY_API_KEY"]

Stick that wherever you're needing to put your API key in the Rails app, then set the environment variable with your API key in this Heroku command: heroku config:set MY_API_KEY=some_long_example_api_key_09823098270098 将其粘贴在需要将API密钥放入Rails应用程序中的任何位置,然后在此Heroku命令中使用API​​密钥设置环境变量: heroku config:set MY_API_KEY=some_long_example_api_key_09823098270098

Now in your Rails app when you use ENV["MY_API_KEY"] it will insert in place the value some_long_example_api_key_09823098270098 when your app is running on Heroku. 现在,当您使用ENV["MY_API_KEY"]在Rails应用程序中时,当您的应用程序在Heroku上运行时,它将在位置插入值some_long_example_api_key_09823098270098

If you're trying to reference the environment variable within a .js.erb file you would need to write it as <%= ENV["MY_API_KEY"] %> 如果尝试引用.js.erb文件中的环境变量,则需要将其写为<%= ENV["MY_API_KEY"] %>

Heroku documentation Heroku文档

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

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