Ответ 1
Вы можете проверить content-type
ответа, как показано в этом примере MDN:
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
});
}
});
Если вам нужно быть абсолютно уверенным, что содержимое является допустимым JSON (и не доверяете заголовкам), вы всегда можете просто принять ответ как text
и проанализировать его самостоятельно:
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
}
});
Асинхронный /Await
Если вы используете async/await
, вы можете написать его более линейно:
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
}
}