How to Fix the “Access to XMLHttpRequest” CORS Error
An “Access to XMLHttpRequest at ‘…’ … has been blocked by CORS policy” error usually means the API response does not permit your frontend’s origin, request method, headers, or credentials. The fix normally belongs on the API server or a same-origin backend proxy, not in an extra header added to your JavaScript request. Start with the complete console message, identify the failed check, and then test both the preflight and the actual API request.
Use the ending of the error message to narrow down the cause:
| Error or Symptom | Likely Cause | Fix |
|---|---|---|
| “No ‘Access-Control-Allow-Origin’ header is present” | The response does not identify an allowed frontend origin | Configure CORS on the server or gateway returning that response |
| “Request header field content-type is not allowed” | The preflight response does not allow a requested header | Allow the headers the browser actually sends |
| “Method … is not allowed” | The preflight response does not allow the requested method | Allow the method required by that API route |
| “Preflight … does not have HTTP ok status” | The preflight was rejected, redirected, or failed upstream | Make the preflight reach a working handler without requiring login |
| A wildcard origin is rejected with credentials | The server uses * for a credentialed request |
Return an explicitly allowed origin and enable server-side credential support |
What the XMLHttpRequest CORS Error Means
Browsers restrict JavaScript from reading responses across origins unless the destination server permits it through Cross-Origin Resource Sharing, or CORS.
An origin consists of the URL’s scheme, hostname, and port. Changing any of those makes the request cross-origin. Two sites can both use HTTPS and still have different origins; different paths on the same origin do not create a CORS boundary.
The server communicates permission through HTTP response headers. Your frontend cannot grant itself permission by sending those headers in its request.
Some requests also require a preflight: the browser first sends an OPTIONS request asking whether the intended method and headers are allowed. Common triggers include an Authorization header, JSON content, or methods such as PUT and DELETE. Even a GET request can require preflight if it includes a non-safelisted header.
If preflight fails, the browser does not send the intended request. If preflight passes, or was unnecessary, the actual response still needs the appropriate CORS headers before JavaScript can read it.
How to Fix the XMLHttpRequest CORS Error
Fix the error by identifying the failing request, resolving URL or server failures, and configuring CORS on the component that answers it.
Step 1: Inspect the Exact Failing Request
- Open your browser’s developer tools and locate the console and network log.
- Enable log preservation if the action navigates or redirects, then reproduce the failure.
- Select the failed request and record: – Its complete request URL. – The frontend’s
Originrequest header. – The HTTP method. – The request headers, especially content type and authorization. – Whether cookies or other browser-managed credentials are intended. - Look for an associated
OPTIONSrequest. Inspect its status, response headers, and any redirect.
For a missing-origin preflight error, the response to OPTIONS must contain an appropriate Access-Control-Allow-Origin header. Adding that header only to the eventual API response does not repair a failed preflight.
Also inspect Access-Control-Request-Method and Access-Control-Request-Headers on the preflight. These show what the browser is asking the server to permit; they are more reliable than assumptions about what your frontend library sends.
Step 2: Correct the URL and Underlying Server Failures First
Before changing CORS policy, establish that the request reaches the intended service.
- Check the frontend’s API URL. Look for a development hostname in a deployed build, an incorrect scheme, or an absolute URL that bypasses your development proxy.
- Inspect redirects. An API request may be redirected to a login page, another hostname, or a canonical URL. Where appropriate, call the intended final API endpoint directly.
- Check the service and gateway logs. A connection failure, certificate problem, unavailable upstream, or application exception can prevent the expected CORS response from being returned.
If no HTTP response arrives, changing application response headers will not repair the transport problem. Restore connectivity or fix the failing service, then reproduce the browser request.
If a response does arrive, determine which component produced it: your application, reverse proxy, API gateway, or identity service. Configure the component actually answering the request.
Step 3: Configure CORS on the API Server
For an existing Express backend, install the CORS middleware in the backend project:
npm install cors
Add the following after your Express application is created, but before authentication middleware, routes, and error handling. Placing it before the body parser also helps ensure parser errors receive CORS headers.
const cors = require("cors");
app.use(cors({
origin: "http://localhost:3000",
methods: ["GET", "POST", "PUT", "DELETE"],
allowedHeaders: ["Content-Type", "Authorization"]
}));
This is a common local-development starting configuration, not a universal allowlist:
- Origin: Replace the example with the requesting frontend’s exact origin, taken from the browser request. An origin contains no URL path or trailing slash. A deployed frontend needs its production origin, not the local development value.
- Methods: Keep the methods required by your API routes. Add another method only when a route actually needs it; listing a method does not create a corresponding route.
- Headers: Compare the allowed headers with the preflight’s requested-header list. Include additional headers only when the browser request requires them.
Application-level Express CORS middleware handles preflight requests. Keeping it ahead of authentication prevents a credential-free preflight from being rejected as an unauthenticated API operation. Keep authentication on the actual protected routes.
For another backend framework, configure its equivalent CORS middleware to return:
- An allowed origin.
- The requested method and headers when preflight requires them.
- The necessary CORS headers on actual API responses, including application errors.
Do not make several layers append their own origin headers to the same response. Multiple Access-Control-Allow-Origin values can make an otherwise valid response fail the browser’s checks.
Step 4: Match Credential Handling to Your Authentication
- Determine whether the request uses a bearer token, cookies, or both. An explicitly supplied bearer token needs the authorization header permitted. It does not, by itself, require cross-origin cookie support.
- For cookie-based sessions, enable cross-origin credentials in the client and server. Axios and XMLHttpRequest expose this through
withCredentials; Fetch has a credentials mode for including cross-origin cookies. In Express CORS middleware, enable thecredentialsoption. - Use an explicit allowed origin for credentialed requests. A wildcard origin cannot authorize the browser to expose a credentialed response.
- Inspect cookie behavior separately. Browser cookie restrictions still apply even when CORS is correctly configured.
Do not enable credentials as a general-purpose fix for a token-only request. Match the settings to the authentication flow you intend to support.
Step 5: Restart and Retest the Real Operation
- Restart the backend or redeploy the changed configuration. Reload any proxy or gateway configuration you edited.
- Repeat the failing browser action with a safe test payload.
- If a preflight occurs, confirm that it passes.
- Inspect the actual API request and response, not just
OPTIONS. - Confirm that your JavaScript can read the expected response body.
A successful transport status alone is not enough. If the response is now readable but says the user is unauthorized, CORS may be fixed while authentication still needs repair.
Preflight results can be cached, so the absence of a new OPTIONS entry does not necessarily mean the browser skipped a required check incorrectly. The decisive result is whether the intended request works in the browser.
What to Do When You Cannot Change the API
If a third-party API does not permit browser access from your origin, frontend code cannot override that decision.
First, check whether the provider offers a browser-supported endpoint, an origin allowlist in its account settings, or an SDK intended for browser use. Configure that supported integration and test the original operation again.
If the provider supports only server-to-server access, use a backend you control:
- Create a backend route that calls the permitted upstream API.
- Have the frontend call that route on its own origin, typically through a relative URL.
- Keep upstream secrets on the backend rather than exposing them to browser code.
- Restrict forwarding to the intended upstream service and approved operations. Do not accept arbitrary destination URLs from callers.
- Test the browser-facing route with both a successful request and an upstream failure.
The browser now talks to your backend on the same origin. Your backend makes the upstream request outside the browser’s CORS enforcement.
A public “CORS proxy” is not an appropriate place to send session cookies, access tokens, or private application data. Use infrastructure you control and retain authentication and access controls on the proxy route.
Local Development, Login Redirects, and Cloud Gateways
Localhost and Development Proxies
A development proxy can create an unexpected origin mismatch. For example, a page opened at http://localhost:3000 may generate an absolute request to http://reviews.test, even though both addresses ultimately reach the same local application.
Choose one consistent browser-facing route:
- Send API requests through the development proxy, with the proxy configured to forward the API paths.
- Or allow the frontend’s actual development origin on the API.
Changing an absolute URL to a relative one helps only if the development server actually forwards that path. Otherwise, the request may hit the frontend server and return HTML instead of API data.
Restart the affected development server or proxy, reload the page through its intended address, and repeat the failing interaction. Check production separately; a local proxy does not automatically become part of a deployed application.
OAuth Authorization Redirects
For Auth0’s /authorize endpoint, initiate interactive login through its supported SDK or top-level browser navigation, not an XMLHttpRequest to fetch the login page.
The authorization flow navigates the user to sign in and then returns them to the registered callback. Complete that flow through the supported integration before making authenticated calls to your API.
Verify the login navigation and the subsequent API request separately. This distinction concerns the interactive authorization endpoint; not every OAuth-related endpoint rejects browser requests.
AWS Gateways and Reverse Proxies
CORS must cover the response the browser receives, not merely the response your application would have returned.
In a token-authenticated AWS and Node deployment, a successful OPTIONS response can coexist with a CORS failure on the authenticated request. A gateway may answer preflight successfully, then reject the real request before it reaches Node.
Inspect gateway-generated authentication failures, upstream errors, redirects, and application responses. Make sure each response-producing layer applies the intended policy without duplicating headers.
After changing the configuration, test both an authorized request and a deliberately unauthorized request using test credentials. The authorized call should work; the unauthorized call should remain rejected, with its error readable by the permitted frontend.
Why Common Browser-Side Workarounds Fail
Browser-side headers, no-CORS mode, wildcards, and disabled security protections cannot replace server authorization or repair the application.
Adding CORS Response Headers to the Request
Putting Access-Control-Allow-Origin in an Axios, Fetch, or XMLHttpRequest request does not grant access. That permission must come from the responding server.
An unnecessary custom request header can also trigger a preflight, creating another check rather than solving the original one.
Using Fetch’s No-CORS Mode
Fetch’s no-CORS mode is not a way to read an API that has denied cross-origin access. It produces an opaque response for the relevant cross-origin request, so application code cannot read the response body as normal API data.
Likewise, explicitly selecting Fetch’s CORS mode does not make the server authorize your origin.
Adding a Wildcard Without Checking the Failure
Adding a wildcard Access-Control-Allow-Origin header may not resolve a site’s CORS failure. The request may still fail because of credentials, disallowed headers, an unsupported method, a redirect, or an error response generated elsewhere.
Use a wildcard only when the resource is intentionally readable by any origin without credentialed access. It is not a substitute for diagnosing a private application’s request.
Disabling Browser Security
A browser extension or a browser launched with security protections disabled can hide the symptom on one machine. It does not fix the application for users and weakens the environment used for testing.
Keep browser protections enabled and repair the response policy or request architecture.
How to Confirm and Prevent CORS Failures
Before considering the fix complete, check that:
- The frontend receives the intended API data, not an HTML login page or frontend fallback.
- Protected routes still enforce authentication.
- Application and gateway errors remain readable by the permitted frontend.
- Development and production origins are configured intentionally.
- Each response has a single valid origin policy.
- Caches distinguish responses by origin when the server selects an allowed origin dynamically.
Keep origin allowlists explicit, and do not reflect every incoming origin without validating it. Review the CORS configuration whenever you add a frontend hostname, change an API gateway, introduce a request header, or alter authentication.
CORS is not authentication, authorization, or a complete defense against cross-site request forgery. It governs browser access to responses; other clients can still contact an exposed service, and some browser requests can cause side effects without making their responses readable.
Next, repeat the original failing workflow from the deployed frontend and verify the response in both the network log and application code.
Frequently Asked Questions
Why Does an Axios POST Fail When a Fetch Login Request Works?
An Axios POST can fail CORS even when a Fetch login request succeeds because they may use different destinations, headers, methods, or credential settings. A successful login request does not prove that another API route permits the same frontend. Compare the actual requests in the browser’s network log rather than treating the library choice as the cause.
Why Does the Request Work in an API Client but Not the Browser?
Standalone API clients generally do not enforce the browser’s same-origin policy. A successful request there does not prove that browser JavaScript is permitted to read the response. Inspect the browser request’s origin and the server’s CORS response headers.
Can a CORS Error Mean the Request Already Ran?
Yes, a request that did not require preflight, or that passed preflight, may reach the server and change data before the browser blocks access to its response. Check server logs or application state before retrying a payment, submission, or other non-idempotent operation. A failed required preflight, by contrast, prevents the intended request from being sent.
Why Does One API Work While Another Is Blocked?
Each API controls its own CORS responses, so a browser can accept one API’s response and block a similarly constructed request to another. Different routes or gateway layers can also behave differently within one service. Check the failing target’s request and response independently instead of copying conclusions from a working API.
