简体   繁体   English

如何在Javascript中访问Rails环境变量

[英]How to access Rails environment variables in Javascript

I'm using dotenv and have API keys in my .env file. 我正在使用dotenv,并且在.env文件中有API密钥。 I would like to be able to use that api key in a javascript file, but am not sure how it would have access to Rails' environment variables. 我希望能够在javascript文件中使用该api密钥,但不确定如何访问Rails的环境变量。 I'm not sure if this is correct, but I changed the end of the .js file to .js.erb and used my key as such (but it's not working): 我不确定这是否正确,但是我将.js文件的末尾更改为.js.erb并使用了我的密钥(但它不起作用):

var response = "http://bustime.mta.info/api/where/stops-for-location.json?lat=40.708727599999996&lon=-74.002798&latSpan=0.005&lonSpan=0.005&key=" + "<%= ENV['MTA_API_KEY'] %>";

Any and all help is greatly appreciated. 任何帮助都将不胜感激。

UPDATE: When I ask for what the variable response is, I just get back, " http://bustime.mta.info/api/where/stops-for-location.json?lat=40.708727599999996&lon=-74.002798&latSpan=0.005&lonSpan=0.005&key= " (it's not rendering anything for where the key should go). 更新:当我问什么是变量响应时,我就回来了,“ http://bustime.mta.info/api/where/stops-for-location.json?lat=40.708727599999996&lon=-74.002798&latSpan=0.005 &lonSpan = 0.005&key = “(该键应放在的位置未呈现任何内容)。

I was able to figure it out. 我能够弄清楚。 I didn't need to concatenate between the request and my key variable: 我不需要在请求和关键变量之间进行串联:

var response = "http://bustime.mta.info/api/where/stops-for-location.json?lat=40.708727599999996&lon=-74.002798&latSpan=0.005&lonSpan=0.005&key=<%= ENV['MTA_API_KEY'] %>";

By keeping the key variable in with the string it worked. 通过将key变量保留在字符串中,它可以工作。 Thanks for all the help. 感谢您的所有帮助。

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

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