簡體   English   中英

無法從 Javascript 應用程序訪問 Heroku 配置變量中的 API 密鑰

[英]Unable to access API key in Heroku Config Vars from Javascript app

I am trying to deploy a simple static app consisting of HTML, CSS, and Javascript files to Heroku. 我還添加了“虛擬”composer.json 和 index.php 文件,以允許 static 文件駐留在 static 文件中。 當我 go 到托管頁面時,我看到一個空白屏幕。 控制台 window 如下圖所示。 The files are linked to my GitHub repo, so I am using a.gitignore file to exclude my API key, and saving the API key in Config Vars in Heroku. 該應用程序未找到 API 密鑰並引發錯誤。

Uncaught ReferenceError: MAPBOX_KEY is not defined                 logic.js:68
    at createMap (logic.js:68)
    at createFeatures (logic.js:56)
    at logic.js:9
    at d3.min.js:3
    at Object.<anonymous> (d3.min.js:7)
    at d.call (d3.min.js:4)
    at XMLHttpRequest.e (d3.min.js:7)

到目前為止,我已經嘗試了以下方法:

  • 在 Settings/Config Vars 下的 Heroku 中直接添加了 API 密鑰

  • 使用控制台 window 添加密鑰 heroku config:add MAPBOX_KEY=pk.eyJ1I.....

  • 禁用緩存 web 頁面

  • 在 web 頁面上運行空緩存和硬重新加載

  • 在控制台中運行 heroku 配置並收到以下錯誤:

     heroku config » Error: Missing required flag: » -a, --app APP app to run command against » See more help with --help

我已經搜索了文檔和堆棧溢出,但在 Heroku 中找不到有關 Javascript 的 API 密鑰的任何信息。 我是否需要向 my.js 或 .html 文件添加其他代碼,以便應用程序在 Heroku 服務器上找到密鑰? 下面是 .js 代碼的一部分,一直到錯誤所在的行。

// +++++ Leaflet Challenge +++++

// store API endpoint inside queryUrl
var queryUrl = "https://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/all_week.geojson";

// make API call to USGS and perform a GET request to the query URL
d3.json(queryUrl, function(data) {
   // after a response, send the data.features object to the createFeatures function
   createFeatures(data.features);
});

// Circle radius function
function circleSize(magnitude) {
   return magnitude **2 * 2000 
};

// Circle color function by depth
function circleColor(depth) {
   switch (true) {
      case (depth > 90):
         return "#d73027"; //red
      case (depth > 70):
         return "#fc8d59"; //darkorange
      case (depth > 50):
         return "#fee08b"; //lightorange
      case (depth > 30):
         return "#d9ef8b"; //yellow
      case (depth > 10):
         return "#91cf60"; //yellowgreen
      default:
         return "#1a9850"; //green
   }
};

function createFeatures(earthquakeData) {

   // define a function and run once for each feature in the features array
   // give each feature a popup describing the place and time of the earthquake
   var earthquakes = L.geoJSON(earthquakeData, {
      onEachFeature: function(feature, layer) {
         layer.bindPopup("<h3>Magnitude: " + feature.properties.mag +"</h3><h3>Depth: " + feature.geometry.coordinates[2] + " km</h3><hr><h4>Location: " + feature.properties.place + "</h4><hr><p>" + new Date(feature.properties.time) + "</p>");
      },

      pointToLayer: function(feature, latlng) {
         return new L.circle(latlng, {
            radius: circleSize(feature.properties.mag),
            fillColor: circleColor(feature.geometry.coordinates[2]),
            color: "black",
            weight: .5,
            fillOpacity: 0.8
         })
      }
   });
  
   // send earthquakes layer to the createMap function
   createMap(earthquakes);
}

function createMap(earthquakes) {

   // define lightmap layer
   var lightmap = L.tileLayer('https://api.mapbox.com/styles/v1/{id}/tiles/{z}/{x}/{y}?access_token={accessToken}', {
      attribution: 'Map data &copy; <a href="https://www.openstreetmap.org/">OpenStreetMap</a> contributors, <a href="https://creativecommons.org/licenses/by-sa/2.0/">CC-BY-SA</a>, Imagery © <a href="https://www.mapbox.com/">Mapbox</a>',
      tileSize: 512,
      maxZoom: 18,
      zoomOffset: -1,
      id: "mapbox/light-v10",  
      accessToken: MAPBOX_KEY
   });

提前感謝您提供的任何幫助。 這是我第一次部署到 Heroku,所以這對我來說是全新的。

Heroku config variables are the classic environment variables at operative system(linux, mac, windows) which are designed to be accessed from backend languages who has access to the operative system like: java, php, nodejs, ruby, python, etc

根據您的片段,您需要在您的香草 javascript 中讀取此環境變量,該變量是在某些 web 瀏覽器中從您的 html 調用的,這是不可能的

在這種情況下,普通 javascript 或純 javascript 不允許訪問某些操作系統資源,例如環境變量。

檢查此鏈接以了解變量如何在 vanilla javascript 中工作:

如何在后端應用程序等前端 js 應用程序中使用變量替換?

快速解決方案

在您的 php 代碼中,在操作系統層的 web 渲染之前讀取此變量,因為 php 能夠做到這一點:

Php 不是我最好的技能,但我確信它有幾個選項可以將此變量注入 static html 或 ZDE9B9ED70EEEFFEE17

如果沒有,您可以在 static 文件中使用簡單的字符串替換:

im_your_file.js

zoomOffset: -1,
id: "mapbox/light-v10",  
accessToken: @@MAPBOX_KEY@@

another_php_file.php

replaceStringInFile("@@MAPBOX_KEY@@")

臟溶液

在另一個 php 文件中使用此替換文件中的內容,並在應用程序啟動前從某個 heroku 步驟調用它

您可以使用純 bash 執行此文件替換,並在某些 heroku 步驟中調用它

優雅的解決方案

Webapck 變量注入

最佳解決方案

Instead of read directly the var in your javascript, yo must publish a kind of rest endpoint in your php app like /settings.php. 此端點必須將此變量和其他變量作為 json 返回。

在您的 javascript 文件中,而不是直接使用變量,使用 /settings.php,您將在 javascript 代碼中擁有所需的變量。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM