User-1262787652 posted
Shopping cart in browser calls API in Apache server to add product to cart using additem.
API controller returns
BadRequest( new { title="errormessage"} )
in case or error and
new { title="Product added successfully to cart"} if OK.
In case of server error apache may return 4xx and 5xx codes with text/html content.
How to show this response in javascript in borwser ?
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));
}
If server or proxy is down, Apache returns html content as error message instead of requested json. In this case response.json() fails.
How to check for non-json response and show responce body in this case?
Code should probably use conditionally response.text() instead of response.json() . ShowMessage() and showErrorMessage() injet text to span in page into bootstrap alert compoment.
Also
if (data == null) > return;
looks ugly.
This is ASP.NET 5 Core MVC application using Apache+Kestrel.