When using AJAX to retrieve JSON data from a webpage, it's essential to set the responseType
to json
. If the data processing is successful, a valid JSON string is returned, which works perfectly.
However, if there's an error on the webpage, instead of returning a JSON string with an error message embedded in it, it actually returns an error string that JavaScript does not recognize as valid JSON. As a result, when checking for response
, it comes back as null. In this scenario, I want to view the response string and identify what the error message entails.
var xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.open("POST", "/someEndpoint");
xhr.send();
xhr.onload = function() {
console.log(xhr.response);
}
(Here's a fiddle where you can reproduce the issue.)
If /someEndpoint
returns legitimate JSON, xhr.response
displays a JavaScript object. However, if it doesn't return valid JSON (such as when the endpoint responds with an error message), then I receive an empty object within xhr.response
. Unfortunately, I encounter difficulties accessing the invalid-JSON error response because trying to access xhr.responseText
triggers the following error:
Uncaught DOMException: Failed to read the 'responseText' property from 'XMLHttpRequest': The value is only accessible if the object's 'responseType' is '' or 'text' (was 'json')
The challenge lies in reading the original HTTP response after conducting the request with responseType="json"
; since responseText
remains inaccessible due to how it was set up.