Page 59 - JavaScript
P. 59
const requestData = {
method : 'getUsers'
};
const usersPromise = fetch('/api', {
method : 'POST',
body : JSON.stringify(requestData)
}).then(response => {
if (!response.ok) {
throw new Error("Got non-2XX response from API server.");
}
return response.json();
}).then(responseData => {
return responseData.users;
});
usersPromise.then(users => {
console.log("Known users: ", users);
}, error => {
console.error("Failed to fetch users due to error: ", error);
});
Displaying the top JavaScript questions of the month from Stack Overflow's
API
We can make an AJAX request to Stack Exchange's API to retrieve a list of the top JavaScript
questions for the month, then present them as a list of links. If the request fails or the returns an
API error, our promise error handling displays the error instead.
6
View live results on HyperWeb.
const url =
'http://api.stackexchange.com/2.2/questions?site=stackoverflow' +
'&tagged=javascript&sort=month&filter=unsafe&key=gik4BOCMC7J9doavgYteRw((';
fetch(url).then(response => response.json()).then(data => {
if (data.error_message) {
throw new Error(data.error_message);
}
const list = document.createElement('ol');
document.body.appendChild(list);
for (const {title, link} of data.items) {
const entry = document.createElement('li');
const hyperlink = document.createElement('a');
entry.appendChild(hyperlink);
list.appendChild(entry);
hyperlink.textContent = title;
hyperlink.href = link;
}
}).then(null, error => {
const message = document.createElement('pre');
document.body.appendChild(message);
message.style.color = 'red';
https://riptutorial.com/ 16

