I am trying to print to the console (in order to later handle those edge cases) the response status of my fetch query. However, the only console.log call that works is the one in the 'breaches' function. I get no errors when an account exists in the HIBP db, but I get a 'Request failed: TypeError: response.json is not a function at json' error when the account is not in the db. What am I doing wrong? I got the error handling code from the Google Web Dev articles.
function createNode(element) {
return document.createElement(element);
}
function append(parent, el) {
return parent.appendChild(el);
}
function status(response) {
if (response.status >= 200 && response.status < 300) {
return Promise.resolve(response)
console.log('all is good');
} else if (response.status == 404) {
return Promise.resolve(response.statusText)
console.log('no breaches');
} else if (response.status == 400) {
return Promise.resolve(response.statusText)
console.log('bad req');
} else {
return Promise.reject(new Error(response.statusText))
}
}
function json(response) {
return response.json()
}
var account = document.getElementById('account'),
results = document.getElementById('results');
account.addEventListener("keyup", keyupEvent);
function keyupEvent() {
event.preventDefault();
if (event.key === "Enter") {
fetch('https://haveibeenpwned.com/api/v2/breachedaccount/' + account.value, {
timeout: 1500,
userAgent: 'test'
})
.then(status)
.then(json)
.then(function(breaches) {
console.log('Status Code: ' + breaches.status);
let span = createNode('span');
return breaches.forEach(function(check) {
span.innerHTML = `${check.Name}<br/>`;
append(results, span)
})
}).catch(function(error) {
console.log('Request failed:', error);
});
}
}
if (response.status >= 200 && response.status < 300) {
=>if (response.ok)
– T.J. Crowderconsole.log
s instatus
will never be executed, as they're after thereturn
in each branch. – T.J. Crowderstatus
function has no need to create new promises, just have it directly (and synchronously) return the desired result, orthrow
for the finalelse
clause. Creating additional promises like this is a common promise anti-pattern. – Alnitak