Here is the code snippet to consider:
fetch('https://api.flickr.com/services/rest/?method=flickr.photos.search' +
'&api_key=thiskeyshouldgivemeanerror&text=dog&format=json' +
'&per_page=24&nojsoncallback=1')
.then(function(rsp) {
// The response shown in the first console.log does not match my expectations
console.log(rsp);
if(rsp.stat !== "ok") {
throw new Error(rsp.message);
}
else {
return rsp.json();
}
})
.then(function(rsp) {
// Here's the output I'm looking for: "{stat: "fail", code: 100, message: "Invalid API Key (Key not found)"}"
console.log(rsp);
})
.catch(function(err) {
alert("Encountered an issue. " + err);
});
I am attempting to catch any errors and display the corresponding JSON error message from the response. However, the format of the response differs between the two console.logs. How can I ensure the response matches my expectation from the start?
In addition, why does the initial response show "ok" despite the absence of a valid API key?
Lastly, what is the reason behind needing to call rsp.json() to retrieve the correct JSON data in the second instance when it should have already been in JSON format?