Edit: I just realized this is a duplicate of Recommended solution for AJAX, CORS, Chrome & HTTP error codes (401,403,404,500), and he tried the idea I propose at the end. But I can't tell if he succeeded (dud user?), and no one else has posted a solution or even a comment, so I think it's worth fishing for new answers.
Problem:
422 Unprocessable Entity
, along with JSON information about the errors. The idea is that my app could receive this error information and handle it appropriately in the UI.Showing that the browser received the 401
status code but treated it as a CORS security error:
The response object, showing that my code cannot access the response data (data: ""
, status: 0
):
How have other people handled this limitation? My best guess right now is to hijack an HTTP "success" code (2XX
) as an error code, and then include the error information in the response. This prevents me from using the ajax error handlers in a normal way, but I'm handling this as a global ajax filter anyway, so this filter would capture the deviant success code and trigger the error handlers instead.
Very late answer but in case someone wants to check whether an error occurred while sending an XMLHttpRequest
and then take appropriate actions (on the CLIENT side), then this is a quick workaround:
try{
request.send();
}catch(err){
if(e.toString().startsWith("NetworkError")){
//pasre the string to check error code
//and take appropriate actions
}
}
This is needed because the onreadystatechange
function doesn't get executed when a NetworkError
occurs and, in fact, the whole script is terminated.
The console message indicates that the server isn't sending the required Access-Control-Allow-Origin
header when it sends the 401 response code.
You won't be able to use the CORS error handler to inject content into the DOM unless you fix that.
The server is likely sending the header correctly on responses with a 200 response code. It needs to do it for other response codes, though, if you wish to use data from those response codes.
Fix that on the server end before making design compromises on the client side. That may solve your problem straight away.
It seems it's an opaque response where you can't obtain the headers or the response. And everything is set to null or empty.
https://developer.mozilla.org/en-US/docs/Web/API/Response/type
Or maybe in the server you should add:
Access-Control-Allow-Origin: *