首页 > 解决方案 > API请求在heroku上无法正常工作

问题描述

我正在编写一个 node.js 应用程序,我需要将它部署在 heroku 上。在其中,我得到了 3 个 API,其中一个需要 Rapidapi 的 API 密钥。在我的本地目录中,一切正常。但是,一旦我将我的应用程序上传到 heroku,需要 API 密钥的应用程序就不再工作了。

这是我的代码:

//where i am accessing my api 
fetch(`/geodb?namePrefix=${city}`).then(response => { //fetching country data to city name

        response.json().then(response => {
        response.json = response;
        var citylenght = Object.keys(response.data).length;
        } 
        
        
//and here is the actual fetch request:
 app.get('/geodb', async (request, response) => {

  let cityname = request.query.namePrefix; //getting parameter for the url

  let api_response = await fetch(`https://wft-geo-db.p.rapidapi.com/v1/geo/cities?namePrefix=${cityname}`, {
    "method": "GET",
    "headers": {
      "x-rapidapi-host": "wft-geo-db.p.rapidapi.com",
      "x-rapidapi-key": process.env.API_KEY //loading api key from .env file
    }
    
  });
  let json = await api_response.json();
  response.json(json);
  });
  
  

在我的本地主机上一切正常,但是当我在 heroku 上访问我的应用程序时,浏览器控制台会显示以下内容:

> Uncaught (in promise) TypeError: Cannot convert undefined or null to
> object
>     at Function.keys (<anonymous>)
>     at api.js:13 (anonymous) @ api.js:13 Promise.then (async) (anonymous) @ api.js:11 Promise.then (async) lookup @ api.js:9
> receiveData @ listeners.js:7 onclick @ (index):43 (anonymous) @
> (index):187

这告诉我该应用程序无法访问 api 数据,这就是答案未定义的原因。heroku 日志也没有显示任何错误。

顺便说一句:当我只使用其他 2 个不需要任何 api 密钥的 api 并且我没有定义任何标头时,一切正常。

如果你能帮助我,我会非常高兴,因为我需要尽快完成。

谢谢!

标签: javascriptnode.jsapirestheroku

解决方案


在 Heroku 上,您在应用程序配置中设置环境变量,而不是通过上传.env. heroku config如果您使用 CLI 工具,则可以使用 Web 界面或命令。

从您的文件中创建密钥“API_KEY”和它应该是的值.env(并且可能不部署该文件,它们通常保留在本地,不包含在源代码控制中或部署到托管平台。这部分只是建议!)


推荐阅读