javascript - 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 并且我没有定义任何标头时,一切正常。
如果你能帮助我,我会非常高兴,因为我需要尽快完成。
谢谢!
解决方案
在 Heroku 上,您在应用程序配置中设置环境变量,而不是通过上传.env
. heroku config
如果您使用 CLI 工具,则可以使用 Web 界面或命令。
从您的文件中创建密钥“API_KEY”和它应该是的值.env
(并且可能不部署该文件,它们通常保留在本地,不包含在源代码控制中或部署到托管平台。这部分只是建议!)
推荐阅读
- php - php 路由不包括 routes.php 文件
- django - 使用 agregates 计算并保存在 django 上的表字段中
- r - 字符串到数字的转换
- r - 将多个具有 R 中名称的 Excel 文件作为列表导入
- c - C语言声明
- javascript - 如何通过 touchspin 连续更改 div 的大小
- r - R中没有Y变量的分组条形图
- xml - 如何在 Powershell 中使用 Select-Xml 打印 xml 节点元素的内容?
- anypoint-studio - 无法从项目库(jar)中引用 Mule 4 dataweave 中的 DWL 脚本文件
- python - 如何更新大型 mongodb 集合?