CORS Problems with XAMPP Server and React Frontend Setup

I am currently running a XAMPP server locally at http://localhost on port 80, which serves an API located in the folder kiosk2/api, where api.php acts as the root file. The corresponding .htaccess configuration in kiosk2/api is as follows:

Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Accept"
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE, OPTIONS"

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-l
RewriteRule !^src($|/) api.php [L]

Additionally, I have a React application running on localhost:5173 using Vite. When I send a request to an endpoint without specific headers, the operation succeeds:

const response = await fetch(`http://localhost/kiosk2/api/items`);

However, upon attempting to include an authorization token in a different request, I encounter a CORS error:

const responseWithAuth = await fetch(url, {
    headers: {
      Authorization: "Basic " + btoa(user + ":" + password),
    },
});

The following error message appears in the browser:

“Access to fetch at ‘http://localhost/kiosk2/api/login’ from origin ‘http://localhost:5173’ has been blocked by CORS policy: Response to preflight request doesn’t pass access control check: It does not have HTTP ok status.”

I’m seeking assistance to resolve this issue.

Hey there! Isn’t it frustrating when these CORS problems pop up? Have you tried adjusting the server-side code to handle OPTIONS requests specifically? Sometimes, tweaking the backend’s response status for preflight checks helps. Also, are you running any proxies that might be affecting this? Curious what you’ve tried so far!

It seems that the CORS policy for preflight requests, which are often done for POST or requests with headers like Authorization, might not be properly handled by your server. Since you are dealing with an Authorization header, the browser sends a preflight request (OPTIONS) to check if the server permits the POST or PUT method. Make sure your server is set explicitly to process OPTIONS requests and return an HTTP 200 status and include the necessary headers in its response for CORS compliance.

Make sure your .htaccess is properly configured for OPTIONS method. Also, consider using a CORS middleware if your server supports it. If that doesn’t work, some folks use browser extensions temporairly to bypass CORS for local debugging. But better fix the server config ultimately. Hope this helps!