si potrebbe verificare la content-type
della risposta, come mostrato nella this MDN example:
fetch(myRequest).then(response => {
const contentType = response.headers.get("content-type");
if (contentType && contentType.indexOf("application/json") !== -1) {
return response.json().then(data => {
// process your JSON data further
});
} else {
return response.text().then(text => {
// this is text, do something with it
});
}
});
Se avete bisogno di essere assolutamente sicuri che il contenuto è JSON valido (e don' t fidati delle intestazioni), puoi sempre accettare la risposta come text
e analizzare da soli:
fetch(myRequest)
.then(response => response.text())
.then(text => {
try {
const data = JSON.parse(text);
// Do your JSON handling here
} catch(err) {
// It is text, do you text handling here
}
});
asincrone/attendono
Se stai usando async/await
, si potrebbe scrivere in modo più lineare:
async function myFetch(myRequest) {
try {
const reponse = await fetch(myRequest); // Fetch the resource
const text = await response.text(); // Parse it as text
const data = JSON.parse(text); // Try to parse it as json
// Do your JSON handling here
} catch(err) {
// This probably means your response is text, do you text handling here
}
}
http: // StackOverflow .com/a/20392392/402037 – Andreas