有没有办法从用户输入中获取带有端点的 API?

Is there a way to fetch an API with endpoints from user input?

我懒得解释这个。所以,基本上,我正在制作另一个冠状病毒追踪器,我希望用户能够在表单中输入他们国家的名称(“搜索框”以使其更易于理解)。按回车键后,数据将从 API 和 jQuery 中提取,如下所示: https://api.covid19api.com/country/<USER_INPUT> 并且数据将显示在网站上。有没有办法做到这一点?谢谢

如果 API 支持 CORS,当然可以。 运行 用于查看 POC 的代码段。

async function search() {
  const country = document.getElementById("country").value.trim();
  if(!country) return alert("Enter a country.");
  const url = `https://api.covid19api.com/country/${country}`;
  try {
    document.getElementById("output").value = "Fetching...";
    const res = await fetch(url);
    if(!res.ok) throw new Error("Result not OK");
    const data = await res.json();
    document.getElementById("output").value = JSON.stringify(data, null, 2);
  } catch(err) {
    alert(err);
  }
}
* {
  box-sizing: border-box;
}

label {
  display: block;
}

textarea {
  width: 100%;
  display: block;
}
<form onsubmit="search(); event.preventDefault(); return false">
  <label>Country: <input type=search placeholder="Country code (e.g. FI)" id="country"></label>
  <button type=submit>Search</button>
</form>
<hr />
<textarea readonly id="output" rows=10 placeholder="Results appear here"></textarea>