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);
}
);
what i am trying to do is to handle error if the email is not registered on the URL that I try to GET request. When the email is not register yet and return code 404, it will not display as I set in else
.
console.log(data.ok)
showed code 200 in console if I append registered email on URL, but if I append unregistered email, I will get this in console:
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 do not know why it did not display as I want if the email is not registered and response code is 404.
How this works: GET request URL exists => 200 OK GET request URL doesn't exist => 404 not found Your name is not registered yet and the associated URL doesn't exist. So the programs skips the else block in favour of error block. My opinion: I would redo the API appropriately (the name should be a parameter)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.