您可以检查响应,如以下 MDN 示例所示:content-type
fetch(myRequest).then(response => {
const contentType = response.headers.get("content-type");
if (contentType && contentType.indexOf("application/json") !== -1) {
return response.json().then(data => {
// The response was a JSON object
// Process your data as a JavaScript object
});
} else {
return response.text().then(text => {
// The response wasn't a JSON object
// Process your text as a String
});
}
});
如果您需要绝对确定内容是有效的JSON(并且不信任标头),则始终可以接受响应并自行解析:text
fetch(myRequest)
.then(response => response.text()) // Parse the response as text
.then(text => {
try {
const data = JSON.parse(text); // Try to parse the response as JSON
// The response was a JSON object
// Do your JSON handling here
} catch(err) {
// The response wasn't a JSON object
// Do your text handling here
}
});
异步/等待
如果你正在使用 ,你可以用更线性的方式编写它:async/await
async function myFetch(myRequest) {
try {
const reponse = await fetch(myRequest);
const text = await response.text(); // Parse it as text
const data = JSON.parse(text); // Try to parse it as JSON
// The response was a JSON object
// Do your JSON handling here
} catch(err) {
// The response wasn't a JSON object
// Do your text handling here
}
}