您可以检查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
}
});
异步/等待
如果您使用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
}
}