当我单击按钮时,我希望从端点返回数据。
但是,我得到这个错误:
Id:undefinedURL:undefinedName:undefinedDescription:undefined
这是我的功能
//fetch
function RetrieveEntries(){
fetch("http://vk-data:8003/v1/entries/", {
headers:{
'x_auth': 'gdjsjaosh-hkds-dhjsk-hjjdbah',
'data': 'access-control',
}}
)
.then(function(response) {
return response.json()
})
.then((response) => {
var results = document.getElementById('results')
console.log(response)
response.forEach(element => {
results.innerHTML = 'Id:' + response.id + 'Type:' + response.type + "Name:" + response.name "<br><br>"
});
})
.catch(error => console.error(error))
}
您将在每次迭代中替换innerHTML
。你是想附加上去吗?
您还应该使用来自每个元素迭代的属性。试图在response
(数组)上访问它们是您获得undefined
值的原因。
要格式化结果,您可能希望使用类似<dl>
的东西,可以轻松地使用CSS样式。
const createElement = (tag, ...content) => {
const el = document.createElement(tag);
el.append(...content);
return el;
};
const formatData = ({ id, url, name, description }) =>
createElement(
"dl",
createElement(
"div",
createElement("dt", "Id"),
createElement("dd", id)
),
createElement(
"div",
createElement("dt", "URL"),
createElement("dd", Object.assign(createElement("a", url), { href: url }))
),
createElement(
"div",
createElement("dt", "Description"),
createElement("dd", description)
)
);
然后获取数据,将数组映射到格式化的元素,并将它们附加到结果div…
const results = document.getElementById("results");
// empty the <div> for a fresh start
results.innerHTML = "";
fetch("http://vk-data:8003/v1/entries/", {
headers: {
x_auth: "gdjsjaosh-hkds-dhjsk-hjjdbah",
data: "access-control",
},
})
.then((res) => (res.ok ? res.json() : Promise.reject(res)))
.then((data) => {
results.append(
...data.flatMap((entry) => [
formatData(entry),
document.createElement("br"),
document.createElement("br"), // could also just use CSS margin
])
);
})
.catch(console.error);