Using Fetch to Display Questions from the Stack Overflow API
suggest changeThis expects document.body to exist. Use https. An error payload may not have items, and a question may not have owner.
const url =
'https://api.stackexchange.com/2.2/questions?site=stackoverflow&tagged=javascript';
const questionList = document.createElement('ul');
document.body.appendChild(questionList);
const responseData = fetch(url).then(response => {
if (!response.ok) {
throw new Error('Stack Exchange request failed');
}
return response.json();
});
responseData.then(({items}) => {
for (const {title, score, owner, link} of items) {
const listItem = document.createElement('li');
questionList.appendChild(listItem);
const a = document.createElement('a');
listItem.appendChild(a);
a.href = link;
a.textContent = `[${score}] ${title} (by ${owner && owner.display_name || 'somebody'})`
}
});
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents