est-il possible de donner une chaîne JSON par défaut (alternative) si elle ne peut pas se connecter à la Fetch URL?
3 Réponses :
Vous pouvez utiliser un p> essayer code> / bloc code> bloc let Response3;
try {
Response3 = await fetch(`https://example.com/match/get?_=&id=${matchlist[2].id}`);
if (!Response3.ok)
throw new Error(Response3.statusText);
} catch (e) {
Response3 = {
prop: 'default json'
}
}
// do something with the Response3 data here.
Vous pouvez utiliser une promesse comme une promesse en ajoutant .Chen code> à la fin de la recherche et de la lecture de la réponse. const Response3 = await fetch(url).then((response) => {
//Check the response coming back to see if it was successful
if (response.status === 200) {
return response.json(); //returns data returned from call
} else {
// if not successful, make your other call
fetch(otherUrl).then(res2 => {
if (res2.status === 200) {
return response.json(); //if your second call was successful, return the data
}
})
}
})
Ici vous allez
async function checkResponse(url) {
const Response3 = await fetch(url);
// thats mean pleas check the status of Response3 if it is equal to 404 (cannot connect to server)
// otherwise put the same response (or the data you want like: Response3,players)
let Response4 =
Response3.status === 404 ? 'Cannot connect to the server' : Response3;
/*
// or if you like if statment
let Response4 = Response3;
if (Response3.status === 404) {
Response4 = 'Cannot connect to the server';
}
*/
console.log(Response4);
}
checkResponse();