I have an XmlHttpRequestUpload
with a listener on the load
event:
xhr.upload.addEventListener('load', () => {
if (xhr.status === 200) {
resolve(UPLOAD_OK);
}
else {
const message = JSON.parse(xhr.response)?.error;
reject(new APIError(xhr.status, xhr.statusText, message));
}
});
When I call JSON.parse(xhr.response)
, I get an exception:
Uncaught SyntaxError: JSON.parse: unexpected end of data at line 1 column 1 of the JSON data
This is the exception you'd expect from calling JSON.parse
on the empty string, but what I see as the response body in the browser console is {"error": "Already exists"}
—which is the response I am expecting.
Why does this happen? Shouldn't the response be set by the time the load
event fires? If not, where is this documented and what event is the correct event for getting the response?
Why does this happen? Shouldn't the response be set by the time the load event fires? If not, where is this documented
The XMLHttpRequestUpload: load event
is fired when the upload completes successfully. The full response is usually not received.
and what event is the correct event for getting the response?
You want to register a XMLHttpRequest: load event
. This event is fired when the whole request including the response completes successfully.