【发布时间】:2021-06-27 13:22:24
【问题描述】:
我正在建立一个网站,用户可以在其中根据成分搜索食谱。
我创建了一个 MySQL 数据库,由两个表(配料和食谱)组成,可以通过 Heroku 上托管的 node.js 后端服务器访问。
当用户在搜索栏中输入成分时,这些成分用于向用户提供建议。每次用户更改输入时,都会重新加载这些建议。
但是,我遇到了一个问题,例如在关闭计算机后第一次打开网站时,建议可能会在 1 分钟或 30 秒后出现,然后会弹出,显示立即为之前的输入提供所有建议。
我的意思是前端发送输入的每个请求,但服务器仅在大约 1 分钟后立即响应所有请求。之后,看起来一切正常,并且不再出现此错误。我怀疑 API 第一次加载只是需要时间,但我不知道如何修复它。
和一个sn-p的代码:
$("#searchBar").on("input", () => {
var research = $('#searchBar').val();
if(research == null || research == ""){
$("#searchSuggestions").empty();
$("#searchSuggestions").css("display", `none`)
}else{
fetch(`https://babasrecipes.herokuapp.com/ingredients/${research}`, {method : "POST"})
.then(res => res.json())
.then(data => {
$("#searchSuggestions").empty();
var dataLength = data.length;
var heightSug = dataLength*5;
if(dataLength == 0){
$("#searchSuggestions").empty();
$("#searchSuggestions").css("display", `none`);
}else{
$("#searchSuggestions").css("height", `${heightSug}vh`);
$("#searchSuggestions").css("display", `flex`)
for(var i = 0; i < dataLength;i++){
var noSpaceName = data[i].name.replace(/ /g, "-");
$("#searchSuggestions").append(`<p class="suggestion" onclick="suggestionClick(this)" id="${noSpaceName}">${data[i].name}</p>`);
}
}
})
}
})
@import url('https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,100;0,400;0,500;0,600;0,700;0,900;1,100;1,400&display=swap');
*{
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: 'Montserrat', sans-serif;
}
.search{
position: relative;
border: 1px solid black;
border-radius: 3px;
left: 0.7vw;
top: 5vh;
height: 5vh;
}
#searchBar{
width: 24vw;
padding: 10px;
}
#searchSuggestions{
position: relative;
background-color: white;
left: 0.7vw;
top: 5vh;
height: 36vh;
width: 24vw;
z-index: 100;
border: 1px solid black;
border-bottom-left-radius: 3px;
border-bottom-right-radius: 3px;
border-top: none;
display: none;
flex-direction: column;
padding-top: 5px;
}
.suggestion{
width: 23.8vw;
height: 15vh;
vertical-align: middle;
background-color: white;
text-overflow: hidden;
padding-left: 10px;
}
.suggestion:hover{
background-color:rgb(235, 235, 235);
cursor: pointer;
}
<!DOCTYPE html>
<html>
<header>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</header>
<body>
<div id="searchPart">
<label for="searchBar" style="display: none;">Add ingredients to your search</label>
<input id="searchBar" type="text" class="search" placeholder="Add ingredients...">
<div id="searchSuggestions"></div>
</div>
</body>
</html>
我的网站托管在 Firebase 上,问题不是来自我的笔记本电脑,因为我在另一台连接到不同位置的不同 wifi 的计算机上尝试网站时遇到了同样的问题。
数据库中有大约 1200 种成分,但在本地一切正常。
有人可以帮助我理解为什么在我第一次加载网站时这些建议需要一些时间才能出现以及如何防止它?
编辑:为了清楚一切是如何工作的,我将前端文件托管在 Firebase 上,这些文件由用户加载,然后从那里,前端从 heroku 托管的 node.js 脚本中获取 api
【问题讨论】:
-
从未使用过Firebase,但听起来您的应用程序的后端在一段时间未使用后被停用,并且在您再次使用时需要一段时间才能重新激活。
-
网站加载后我是否可以重新激活我的应用程序的后端?
标签: javascript html database heroku fetch