【问题标题】:How to pass an ENV variable into script tag如何将 ENV 变量传递到脚本标签
【发布时间】:2016-07-24 17:28:00
【问题描述】:

我正在尝试将我的 application.yml 文件中的 api 密钥传递给谷歌地图的 js 脚本标签,这可能吗?如果没有,处理这个问题的最佳方法是什么?另外,我正在使用 Figaro gem 来存储 ENV 变量。提前致谢。

    <% if @location.latitude.present? && @location.longitude.present? %>
  <script>
    var myLatLng = {lat: <%= @location.latitude %>, lng: <%= @location.longitude %>};
    function initAutocomplete() {
    var map = new google.maps.Map(document.getElementById('map'), {
      center: myLatLng,
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });

    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      title: '<%= @location.name %>'
    });

    // Create the search box and link it to the UI element.
    var input = document.getElementById('pac-input');
    var searchBox = new google.maps.places.SearchBox(input);
    map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

    // Bias the SearchBox results towards current map's viewport.
    map.addListener('bounds_changed', function() {
      searchBox.setBounds(map.getBounds());
    });

    var markers = [];
    // Listen for the event fired when the user selects a prediction and retrieve
    // more details for that place.
    searchBox.addListener('places_changed', function() {
      var places = searchBox.getPlaces();

      if (places.length == 0) {
        return;
      }

      // Clear out the old markers.
      markers.forEach(function(marker) {
        marker.setMap(null);
      });
      markers = [];

      // For each place, get the icon, name and location.
      var bounds = new google.maps.LatLngBounds();
      places.forEach(function(place) {
        var icon = {
          url: place.icon,
          size: new google.maps.Size(71, 71),
          origin: new google.maps.Point(0, 0),
          anchor: new google.maps.Point(17, 34),
          scaledSize: new google.maps.Size(25, 25)
        };

        // Create a marker for each place.
        markers.push(new google.maps.Marker({
          map: map,
          icon: icon,
          title: place.name,
          position: place.geometry.location
        }));

        if (place.geometry.viewport) {
          // Only geocodes have viewport.
          bounds.union(place.geometry.viewport);
        } else {
          bounds.extend(place.geometry.location);
        }
      });
    map.fitBounds(bounds);
  });
}
  </script>
  <input id="pac-input" class="controls" type="text" placeholder="Search Box">
  <div id="map"></div>
  <script src="https://maps.googleapis.com/maps/api/js.erb?key=MAPS_API_KEY&libraries=places&callback=initAutocomplete"
         async defer></script


<% end %>

错误

https://maps.googleapis.com/maps/api/js.erb?key=&libraries=places&callback=initAutocomplete

这就是我所拥有的,它给了我发布的错误,如果我直接将密钥放入它可以工作。

<script src="https://maps.googleapis.com/maps/api/js.erb?key=<%= ENV['MAPS_API_KEY'] %>&libraries=places&callback=initAutocomplete"
         async defer></script

【问题讨论】:

  • 向我们展示您用于生成页面的代码。

标签: javascript ruby-on-rails figaro-ruby


【解决方案1】:

这对我有用:

<script async defer src=<%="https://maps.googleapis.com/maps/api/js?key=#{ENV['GOOGLE_MAPS_API_KEY']}&callback=initMap"%> type="text/javascript"></script>

【讨论】:

    【解决方案2】:

    您应该能够使用 ERB 将其视为任何其他 ENV 变量:

    ...
    <script src="https://maps.googleapis.com/maps/api/js.erb?key=<%=ENV['MAPS_API_KEY']%>&libraries=places&callback=initAutocomplete"
             async defer></script>
    

    【讨论】:

    • 我试过了,不幸的是它抛出了一个“get”错误。
    • Figaro.env.MAPS_API_KEY 也给出同样的错误?
    • 我会在嵌入的 ruby​​ 标记中实现“Figaro.env.MAPS_API_KEY”吗?
    • 您可以,但我正在尝试找出导致您的错误的原因。如果 figaro 设置正确,它应该给出与 ENV['MAPS_API_KEY'] 相同的值
    • 我相信它的设置正确,它被用于 AWS:ACCESS、SECRET、BUCKET、EMAIL、PASSWORD 和 GEOCODER。
    【解决方案3】:

    试试这个#{ENV['MAPS_API_KEY']},我之前也遇到过类似的问题:

    &lt;script src="https://maps.googleapis.com/maps/api/js.erb?key=&lt;%=#{ENV['MAPS_API_KEY']}%&gt;&amp;libraries=places&amp;callback=initAutocomplete" async defer&gt;&lt;/script&gt;

    【讨论】:

      【解决方案4】:

      我猜你只是不想把你的 api_key 放到一个 html 标签中,让你的密钥容易受到攻击。您可以在 index.html 下尝试以下代码,它对我有用。

      <div id="google">
        <script type="text/javascript">
          import {
            GOOGLE_MAP_API
          } from "<the location you save your apikey>";
      
          function changeSrc() {
            document.getElementById("google").src = `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAP_API}`
          }
        </script>
      </div>

      【讨论】:

        【解决方案5】:

        请注意,如果您使用 Ruby(或 Figaro)并且正在使用 Webpack,则可以通过 HtmlWebpackPlugin 注入它。

        【讨论】:

          【解决方案6】:

          您可以使用数据标签来传递环境变量

          <script id="div" data-key="<%=ENV['MAPS_API_KEY']%>">
            const div = document.getElementById("div");
            console.log(div.dataset.key);
          </script>
          

          【讨论】:

            猜你喜欢
            • 2019-06-10
            • 1970-01-01
            • 2022-01-03
            • 2021-12-13
            • 1970-01-01
            • 2016-10-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多