我正在编程一个Node.js应用程序,我需要在Heroku上部署它。在其中,我得到了3个API,其中一个需要一个API键从rapidapi。在我的本地目录中,一切工作正常。但是,当我把我的应用程序上传到heroku时,需要API密钥的应用程序就不再起作用了。
下面是我的代码:
null
//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);
});
null
在我的本地主机上,一切都很正常,但是当我在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日志也没有显示任何错误。
顺便说一下:当我只使用其他两个不需要任何api键的api时,也没有定义任何头,那么一切都很好。
如果你能帮我,我会很高兴的,因为我需要尽快完成它。
谢啦!
在Heroku上,您可以在应用程序配置中设置环境变量,而不是通过上传.env
。如果使用CLI工具,则可以使用web界面或heroku config
命令。
使键“api_key”和值从.env
文件中获得任何值(可能不部署该文件,它们通常保存在本地,不包括在源代码管理中,也不部署到宿主平台。不过,这部分只是建议!)