app.js
client.request
.get(
'https://url.dev/api/users/${email}',
options
)
.then(
data => {
const userInfo = JSON.parse(data.response).data
if (data.ok) {
var name = userInfo.name;
var initials = name.charAt(0);
document.getElementById("nameInitial").innerHTML = initials;
document.getElementById("name").innerHTML = name;
document.getElementById("email").innerHTML = userInfo.email;
}
else {
var name = "Unknown";
var initials = name.charAt(0);
document.getElementById("nameInitial").innerHTML = initials;
document.getElementById("name").innerHTML = name;
document.getElementById("email").innerHTML = "Unknown"
}
},
error => {
console.error('An error occurred during the request..');
console.error(error);
}
);
My goal is to handle errors when attempting to fetch user information by email. If the email is not registered, a 404 status code will be returned, but for some reason, the display logic in the else
block does not work as expected.
The console.log(data.ok)
shows a response code of 200 when an existing email is used, but returns the following when an unregistered email is used:
Object
attempts: 1
errorSource: "APP"
headers: {date: "Tue, 19 Apr 2021 05:41:27 GMT", content-type: "application/json", transfer-encoding: "chunked", connection: "close", set-cookie: Array(1), …}
response: "{\n \"message\": \"\"\n}"
status: 404
I am unsure why the desired output is not achieved when an unregistered email is used and the response code is 404.