javascript - 显示来自 json API 调用的非 json 响应
问题描述
浏览器中的购物车调用 Apache 服务器中的 API 以使用 additem 将产品添加到购物车:
function addItem(product, quantity) {
fetch('api/addItemToCart', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
product: [product],
quantity: [quantity]
})
})
.then(response => {
if (response.ok) {
return response.json();
}
response.json().then(
json => {
showErrorMessage(json.title);
});
return null;
})
.then((data) => {
if (data == null)
return;
showMessage(data.title);
})
.catch(error => alert('addItem error', error));
}
如果服务器或代理关闭,Apache 将返回 html 内容作为错误消息而不是请求的 json。
在这种情况下 response.json() 失败。
在这种情况下如何检查非 json 响应并显示响应正文?
代码可能应该有条件地使用 response.text() 而不是 response.json() 。
ShowMessage() 和 showErrorMessage() 将页面中的文本插入到引导警报组件中。
还
如果(数据 == null)返回;
看起来很丑。
这是使用 Apache+Kestrel 的 ASP.NET 5 Core MVC 应用程序。