#头条创作挑战赛#
本文同步本人掘金平台的原创翻译:https://juejin.cn/post/6890719051820695565
谷歌扩展程序是个HTML,CSS和JAVASCRIPT应用程序,它可以安装在谷歌浏览器上。
下面的内容,指导感兴趣的人儿创建一个谷歌扩展程序,它允许我们去获取不同国家新型冠状病毒肺炎-covid19案例的信息。
步骤1:创建目录
创建一个名为dist的文件夹,然后创建以下的文件。
步骤2:创建HTML文件
如下内容:
Covid 19
Covid 19
loading...
New cases:
New deaths:
Total cases:
Total recovered:
Total deaths:
Total tests:
Stay Safe and Healthy
复制代码
步骤3:创建JAVASCRIPT文件
JAVASCRIPT文件用来处理API,内容如下:
const api = "https://coronavirus-19-api.herokuapp.com/countries";
const errors = document.querySelector(".errors");
const loading = document.querySelector(".loading");
const cases = document.querySelector(".cases");
const recovered = document.querySelector(".recovered");
const deaths = document.querySelector(".deaths");
const tests=document.querySelector(".tests");
const todayCases=document.querySelector(".todayCases");
const todayDeaths=document.querySelector(".todayDeaths");
const results = document.querySelector(".result-container");
results.style.display = "none";
loading.style.display = "none";
errors.textContent = "";
// grab the form
const form = document.querySelector(".form-data");
// grab the country name
const country = document.querySelector(".country-name");
// declare a method to search by country name
const searchForCountry = async countryName => {
loading.style.display = "block";
errors.textContent = "";
try {
const response = await axios.get(`${api}/${countryName}`);
if(response.data ==="Country not found"){ throw error; }
loading.style.display = "none";
todayCases.textContent = response.data.todayCases;
todayDeaths.textContent = response.data.todayDeaths;
cases.textContent = response.data.cases;
recovered.textContent = response.data.recovered;
deaths.textContent = response.data.deaths;
tests.textContent = response.data.totalTests;
results.style.display = "block";
} catch (error) {
loading.style.display = "none";
results.style.display = "none";
errors.textContent = "We have no data for the country you have requested.";
}
};
// declare a function to handle form submission
const handleSubmit = async e => {
e.preventDefault();
searchForCountry(country.value);
console.log(country.value);
};
form.addEventListener("submit", e => handleSubmit(e));
复制代码
上面,我们创建了一个名为searchForCountry的异步函数,在该函数上,我们可以使用async-await的语法。async await允许我们当正在等待服务端响应的时候,停止执行之后其他相关的代码。在代码片段前使用await关键字,当在执行该代码片段时,它之后的代码将停止执行。
在这个例子中,我们await一个GET请求的响应,然后将响应值赋值给response变量。
Axios是一个很受欢迎的JavaScript库,它可以很好处理HTTP请求,并且可以在浏览器平台和Node.js平台使用。它支持所有的现代浏览器,甚至支持IE8。它是基于promise的,所有很方便我们写async/await代码。
下面是些我们获取数据的API: