我正在尝试访问https://api.open5e.com以创建一个搜索工具,我可以执行获取请求,例如获取https://api.open5e.com/monsters/?type=dragon
这将返回我需要的信息,但我正在尝试以编程方式完成,这样我就可以轻松地应用不同的过滤器
但是,无论我使用哪种字符串组合,我都会得到一个"NetworkError when to fetch resource“。
const APILINKS = [
'https://api.open5e.com/monsters/?',
'https://api.open5e.com/spells/?',
'https://api.open5e.com/weapons/?'
];
async function populateList(url, query) {
document.getElementById("queryResults").innerHTML = "<p>Loading data</p>";
console.log(APILINKS[url] + query);
let link = "https://api.open5e.com/monsters/?" + query
//let response = await fetch(link);
//let response = await fetch(APILINKS[url] + query);
//let response = await fetch('https://api.open5e.com/monsters/?' + query);
//let response = await fetch('https://api.open5e.com/monsters/?type=dragon');
if (response.ok) { // if HTTP-status is 200-299
let json = await response.json();
let count = json['count'];
console.log(count);
response = await fetch(link + "&limit=" + count);
//response = await fetch(APILINKS[url] + query + "&limit=" + count);
//response = await fetch('https://api.open5e.com/monsters/?' + query + "&limit=" + count);
//response = await fetch("https://api.open5e.com/monsters/?type=dragon" + "&limit=" + count);
if (response.ok) { // if HTTP-status is 200-299
json = await response.json();
populateTable(json, ELEMENTLABELS[url]);
} else {
alert("HTTP-Error: " + response.status);
}
} else {
alert("HTTP-Error: " + response.status);
}
}在注释中,我包含了我尝试将连接字符串添加到方法中的不同方法,唯一有效的方法是将字符串硬编码为
有没有人知道为什么这对我不起作用?
编辑:我已经包含了如何在下面的html文件中调用它
<button onclick='populateList(0, "type=dragon")'>Dragons</button>发布于 2021-08-20 17:01:41
只要我在我的浏览器中检查你的代码,它就能工作。在浏览器的开发人员工具中检查控制台/网络错误。一些重构的工作版本(一条建议,分页的资源应该在循环中获取,一些API限制页面大小):
async function populateList(resource, query) {
let queryResults = document.getElementById("queryResults");
queryResults.innerHTML = "<p>Loading data</p>";
let results = [];
let next = "https://api.open5e.com/" + resource + "/?" + query;
while (next !== null) {
let request = await fetch(next);
if (request.ok) { // if HTTP-status is 200-299
let response = await request.json();
results.push(...response["results"]);
next = response["next"];
} else {
queryResults.innerHTML = "<p>Could not load data</p>";
return;
}
}
queryResults.innerHTML = "<p>Loaded " + results.length + " items</p>";
}<button onclick='populateList("monsters", "type=dragon")'>Dragons</button>
<div id="queryResults"></div>
https://stackoverflow.com/questions/68863505
复制相似问题