简体   繁体   English

在Heroku上使用Javascript访问环境变量?

[英]Accessing environment variables in Javascript on Heroku?

I have a ruby/rack app on Heroku serving a site. 我在Heroku上有一个ruby / rack应用程序服务于一个站点。 The site uses Javascript and I want to access an Heroku environment variable in the Javascript file (an API key). 该站点使用Javascript,我想访问Javascript文件中的Heroku环境变量(API密钥)。 I've tried: 我试过了:

process.env.API_KEY
// As well as:
process.env['API_KEY']

But neither seem to work. 但似乎都不起作用。 I get a process is not defined error. 我得到一个没有定义错误的进程。 The above lines of code I got were from a Node.js app running on Heroku. 我得到的上述代码行来自在Heroku上运行的Node.js应用程序。 I thought it'd be the same way to access the keys from a normal js file but it doesn't work. 我认为从普通的js文件访问密钥是一样的,但它不起作用。

You're confused. 你很困惑。 That Javascript is running in visitors' web browsers, not on Heroku, so can't read the server's environment variables. Javascript在访问者的Web浏览器中运行, 而不是在Heroku上运行,因此无法读取服务器的环境变量。 This is a common problem. 这是一个常见问题。 The solution is for your web app to serve the Javascript by a Ruby template, inserting the public API key. 解决方案是让您的Web应用程序通过Ruby模板提供Javascript,插入公共API密钥。

Simple app I wrote has an example. 我写的简单app有一个例子。 https://github.com/hickford/nanoblogger The Javascript file nano.js is rendered by a Ruby erb template https://github.com/hickford/nanoblogger Javascript文件nano.js由Ruby erb模板呈现

var pusher = new Pusher( '<%= Pusher.key %>'); 

The process.env stuff is part of Node.js , and not part of JavaScript, so it's not going to come over to your app. process.env东西是Node.js的一部分 ,而不是JavaScript的一部分,所以它不会转到你的应用程序。

Your rack app should have access to environment variables, however, so if you can pass that value up to something that's accessible to your JavaScript (without exposing it to the user/DOM, if it's sensitive information) then that should work. 但是,您的机架应用程序应该可以访问环境变量,因此,如果您可以将该值传递给JavaScript可访问的内容(不将其暴露给用户/ DOM,如果它是敏感信息)那么这应该可行。

This other answer may point you in a useful direction, or at least clarify if what you're trying to do is possible from JavaScript. 这个其他答案可能会指出您有用的方向,或至少澄清您尝试从JavaScript中做什么。

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

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