How to handle CORS error code?

23,208

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.

Share:
23,208
colllin
Author by

colllin

Updated on July 15, 2022

Comments

  • colllin
    colllin almost 2 years

    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:

    • I send a properly-executed (edit: IMproperly-executed. End of story...) CORS request.
    • The server receives the request and attempts to process it.
    • The server returns an error response, for example a 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.
    • The browser blocks my error handler from getting the response content, or even getting the status code.

    Showing that the browser received the 401 status code but treated it as a CORS security error:

    Status Code 401

    The response object, showing that my code cannot access the response data (data: "", status: 0):

    Obscured Response Object

    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.

  • colllin
    colllin over 9 years
    I said it's a properly-executed CORS request. When the server responds with a success code, the browser processes it correctly.
  • Trott
    Trott over 9 years
    The server is sending the necessary headers on success. It needs to send them on failure too.
  • Trott
    Trott over 9 years
    In other words, you need to send the CORS header on response codes other than 200 if you wish to use the JSON data from response codes other than 200.
  • colllin
    colllin over 4 years
    Is this specific to CORS, or any XHR?
  • progyammer
    progyammer over 4 years
    @colllin I'm not sure but anything that shows a NetworkError in the console can be handled in this manner.