I am using ajax to get JSON data from a web page. So I have set responseType
to be json
. If the web page processes the data successfully, it returns a valid JSON string, which is fine.
But if the web page fails, it returns a JSON string with error message inside, (sorry for the misunderstanding,) it returns an error string, not a json string, so JavaScript does not recognize it as valid JSON string. So if I check for response
, it is null. In that case, I want to see the response string and check what the error message is.
var xhr = new XMLHttpRequest();
xhr.responseType = json;
xhr.open(POST, /someEndpoint);
xhr.send();
xhr.onload = function() {
console.log(xhr.response);
}
(Fiddle to reproduce the issue.)
If /someEndpoint
returns valid JSON, xhr.response
is a JavaScript object. However, if it's not valid JSON (as when the endpoint responds with an error message), then I get an empty object in xhr.response
. I can't access the invalid-JSON error response, because accessing xhr.responseText
gives the 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')
I don't know how to read the original HTTP response after I've run the request with responseType=json
, since responseText
cannot be accessed.