How Axios Handles CORS Preflight Failures

When a Cross-Origin Resource Sharing (CORS) preflight request fails, the Axios HTTP client handles the failure by rejecting the request's Promise with a generic network error. Because browser security sandboxes intentionally block JavaScript from reading details about failed preflight checks, Axios cannot access the server's HTTP status code, headers, or response body. This article explains the technical mechanics behind how Axios processes these preflight failures, what data is made available in the error object, and how developers can identify and resolve these issues.

The Browser Preflight Mechanism

Before Axios transmits a cross-origin HTTP request that is not considered a "simple request" (such as a request using PUT, DELETE, PATCH, custom headers, or application/json content types), the browser automatically dispatches an OPTIONS preflight request.

The preflight request asks the destination server for permission to execute the actual request by checking response headers such as:

Axios operates on top of the browser's native XMLHttpRequest API. If the server fails to respond to the OPTIONS request, returns a non-2xx status code, or fails to provide the required Access-Control-* headers, the browser terminates the transaction before the actual request is sent.

How Axios Represents a Preflight Failure

When the browser blocks a request due to a preflight failure, it does not provide specific CORS error details to the XMLHttpRequest object. Consequently, Axios formats the failure as follows:

axios.post('https://api.example.com/data', { key: 'value' })
  .catch((error) => {
    if (error.response) {
      // Not executed on CORS preflight failure
      console.log(error.response.status);
    } else if (error.request) {
      // Executed: error.request exists, but error.response is undefined
      console.log(error.message); // "Network Error"
      console.log(error.code);    // "ERR_NETWORK"
    }
  });

Handling and Debugging Preflight Failures

Because Axios cannot inspect the root cause of a CORS preflight failure through application code, troubleshooting requires checking the environment outside the Axios error object:

  1. Inspect Browser Developer Tools: The browser's Console and Network tabs are the only client-side locations that log the exact reason for the failure (e.g., missing header, disallowed method, or mismatched origin).
  2. Configure Server-Side Preflight Handling: Ensure the server explicitly handles OPTIONS requests, returns a successful HTTP status code (typically 200 or 204), and sends the required Access-Control-Allow-* headers matching the client request.
  3. Use Interceptors for Generic Fallbacks: Axios interceptors can catch ERR_NETWORK errors globally to trigger network-level fallback logic or alerts, though they cannot distinguish a CORS failure from an offline state or DNS failure programmatically.